Monday, May 24, 2010

What's wrong with this C code?

main(){





char tablero[7][7];


tablero[4][4]="Hola";





printf("Tablero en 5E vale: %d",tablero[4][4]);


getch();





It doesn't take the text string "HOLA", why is that? I want an array [][] where I can store words. Thanks.

What's wrong with this C code?
The first statement,


char tablero[7][7];


creates a 2 dimensional array of letters. The second statement,


tablero[4][4]="Hola";


is effectively trying to insert 4 characters into a space (4, 4) only meant to hold 1 character. Probably what you would want to do would be say,


char tablero[]="Hola";


in this case, tablero[3] would = "a" and tablero[1..2] would = "ol".





Alternatively, you could make that a character pointer array,


char *tablero[7][7]; would would be a 2 dimensional array of character pointers. in this case you could say


*tablero[4][4]="Hola";


and then the pointer at 4, 4 would point to the word.
Reply:Each item in the two dimensional array can only hold one character.





You might try setting tablero[4][0] to "hola" but you'll also need an extra spot for the \0, to indicate end of string.





My Mistake that won't work. You could create a char *wordList[6] which is an array of pointers, and then set wordList[0]="test";
Reply:The type of "Hola" is "const char*", the type of tablero[4][4] is char. What you probably want to do is this:





int main(int argc, char* argv[])


{


const char* table[7];


table[4] = "Hola";


printf("table[4] = \"%s\"\n",table[4]);


return 0;


}
Reply:make tablero a struct


No comments:

Post a Comment