Marmstrong
Marmstrong

Reputation: 1786

Declaration of an array of strings and selecting a single character

I am new to c programming and am trying to print on the screen which key of a keypad is pressed. I have the program to the stage where it prints the row and column number of the key that was pressed. I was thinking if I could declare an array of strings containing all 16 key characters, the row and column numbers could index the array. Here is my feeble attempt at 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 was %c", key[colnum][rownum]);

Upvotes: 2

Views: 2339

Answers (4)

Fahad Naeem
Fahad Naeem

Reputation: 535

key[0] 

means it can hold only one character, while you're holding four characters. For this, you need to declare like following :

char key[4][5]= {"CD.Z", "89AB", "4567", "0123"};

Upvotes: 0

avni
avni

Reputation: 1

define your character array like

char *keys[] = { "CD.Z", "89AB", "4567", "0123" };

after pressing key you may show row and column number as

c = getchar();
for(i=0;i<4;i++)
{
   for(j=0;j<4;j++)
   {
      if(keys[i][j]==c)
      {
           printf("Key of Row %d and Column %d was pressed",i+1,j+1);
      }
   }
}

this might help you.

Upvotes: 0

unwind
unwind

Reputation: 399949

As pointed out by @BLUEPIXY in a comment, your types are wrong.

Also, there's no point in using run-time strcpy() to copy characters around, you can just use compile-time initializers to set up a string array:

const char *keys[] = { "CD.Z", "89AB", "4567", "0123" };

The above declares keys to be an array of char *, which is C's "string type" (it actually only means "pointer to character", but it's commonly used for strings). No length is specified for the array, the compiler automatically computes it based on the initializer expression on the right hand side of the =.

So, indexing like this:

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

will get you the 3rd element (C indexes arrays from 0).

Since pointers can be indexed as well, you can also do:

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

Here, keys[2][1] means "first get the 3rd element from the keys array, then get the 2nd element from that array". This treats a character pointer as an array (by using the [] indexing operator) but that is fine in C, all pointers can be treated as arrays like that.

Upvotes: 4

stefan bachert
stefan bachert

Reputation: 9616

This code fragment should not compile. You tried to copy a char array to a char. The compiler should emit an error

Modify it to this version.

char key[4][5];
strcpy(key[0], "CD.Z");
strcpy(key[1], "89AB");
strcpy(key[2], "4567");
strcpy(key[3], "0123");

Upvotes: 2

Related Questions