-2

The 2d array:

char c[4][3]={{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'}};

As I wanted to get 'def' after running the program, I tried this code:

printf("%s\n",c[1]);

However, the result was 'defghijkl\262'. What's wrong with my code?

A to Z
  • 3
  • 1

1 Answers1

0

You can print def in two ways:

char c[4][4]={{'a','b','c','\0'},{'d','e','f','\0'},{'g','h','i','\0'},{'j','k','l','\0'}};        
printf("%s\n",c[1]);

So, basically printf needs null termination to know where to stop printing

or you can print using a loop without null termination like:

char c[4][3]={{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'}};
for(int i = 0; i < 3; i++)
{
   printf("%c", c[1][i]);
}
S.I.J
  • 979
  • 1
  • 10
  • 22