c - Declaration of an array of strings and selecting a single character -


i new c programming , trying print on screen key of keypad pressed. have program stage prints row , column number of key pressed. thinking if declare array of strings containing 16 key characters, row , column numbers index array. here feeble attempt @ it.

 char key[4];  strcpy(key[0], "cd.z");  strcpy(key[1], "89ab");  strcpy(key[2], "4567");  strcpy(key[3], "0123"); 

...

printf("the key pressed %c", key[colnum][rownum]); 

as pointed out @bluepixy in comment, types wrong.

also, there's no point in using run-time strcpy() copy characters around, can use compile-time initializers set string array:

const char *keys[] = { "cd.z", "89ab", "4567", "0123" }; 

the above declares keys array of char *, c's "string type" (it means "pointer character", it's commonly used strings). no length specified array, compiler automatically computes based on initializer expression on right hand side of =.

so, indexing this:

printf("keys[2] '%s'\n", keys[2]); 

will 3rd element (c indexes arrays 0).

since pointers can indexed well, can do:

printf("second char of '%s' '%c'\n", keys[2], keys[2][1]); 

here, keys[2][1] means "first 3rd element keys array, 2nd element array". treats character pointer array (by using [] indexing operator) fine in c, pointers can treated arrays that.


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -