-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?

2
  • 2
    Null terminator. Commented Feb 4, 2020 at 3:00
  • %s means a string. You have no null terminator so it runs away on you. A 2D array of characters is not a string. Read about printf. Learn C. Commented Feb 4, 2020 at 3:01

1 Answer 1

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.