Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C string initializer doesn't include terminator?

I am a little confused by the following C code snippets:

printf("Peter string is %d bytes\n", sizeof("Peter")); // Peter string is 6 bytes

This tells me that when C compiles a string in double quotes, it will automatically add an extra byte for the null terminator.

printf("Hello '%s'\n", "Peter");

The printf function knows when to stop reading the string "Peter" because it reaches the null terminator, so ...

char myString[2][9] = {"123456789", "123456789" };
printf("myString: %s\n", myString[0]);

Here, printf prints all 18 characters because there's no null terminators (and they wouldn't fit without taking out the 9's). Does C not add the null terminator in a variable definition?

like image 225
too much php Avatar asked Jan 23 '09 02:01

too much php


2 Answers

Your string is [2][9]. Those [9] are ['1', '2', etc... '8', '9']. Because you only gave it room for 9 chars in the first array dimension, and because you used all 9, it has no room to place a '\0' character. redefine your char array:

char string[2][10] = {"123456789", "123456789"};

And it should work.

like image 199
Chris Lutz Avatar answered Oct 17 '22 16:10

Chris Lutz


Sure it does, you just aren't leaving enough room for the '\0' byte. Making it:

char string[2][10] = { "123456789", "123456789" };

Will work as you expect (will just print 9 characters).

like image 35
Sean Bright Avatar answered Oct 17 '22 16:10

Sean Bright