Example Source
#include <stdio.h> int main( void ) { char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'}; printf("%s\n", tab); return 0; }
Compile warning
$ gcc test.c
test.c: In function 'main':
test.c: 5: warning: format '% s' expects type 'char *', but argument 2 has type 'char (*) [3]'
Pointers - pointers
The argument %s for printf tells the function that it will receive a pointer (to a string). A string in C is just a series of bytes terminated by ASCII-Z. The variable tab[2][3] is a pointer. Some compilers give a warning about pointer mismatch. However, the code should still print 12 , because the printf code moves through memory, starting with the pointer that it set (prints characters as it arrives) until it finds a null byte. 1, 2 and \ 0 are adjacent in memory starting from the address represented by the variable tab .
Experiment
As an experiment, what happens when you compile and run the following code:
#include <stdio.h> int main( void ) { char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'}; printf("%s\n", tab[1]); return 0; }
Do not be afraid to experiment. See if you can find the answer based on what you now know. How would you now refer to tab (in the light of the experiment) to get rid of the warning and still display 12 ?
source share