Need help in's about array size

September 6, 2011 at 08:57:27
Specs: Windows 7
hi, i am fairly new to C programming. I am trying the following codes:

char string[14] = "11111111111110";
int s_size = strlen(string);
printf("size is %d\n", s_size);

assuming I have included all the libraries needed in this program. When I compile it, it seems fine...and the result should print "size is 14"....but instead it printed "size is 18". I do not really understand what is wrong but if anyone can help me I totally appreciated thanks!

See More: Need help in C....its about array size

Report •

September 6, 2011 at 09:19:01
There is a fundamental error in your program which probably explains your result. You have declared an array of char of size 14 and are initializing it with a string containing 14 characters. But a C string, which is what "strlen" is looking at, must end with a null character - this is what determines when the string ends. You have initialized char[0] to '1', char[1] to '1', ... char[13] to '0'. But there is no null character at the end of the string (there are no more elements in the array to hold the null character. So as far as C is concerned, your string goes on with the random values contained in memory after the end of your array. It just so happens that, after another 4 characters, it finds a null. Depending upon your platform, C compiler and, no doubt, other factors, it could have taken any number of characters to find that null. (I tried this with gcc on 64-bit Linux and it actually gave the correct result; obviously the memory value immediately after the array happened to be null.)

What you need to do if you want a 14 character string is to make the array 15 characters long. This allows for the terminating null character.

In this case the result was merely a puzzle. In practice this sort of error normally leads to program crashes and/or security problems; it is the infamous "buffer overrun" error.

Report •

September 6, 2011 at 15:07:11
Thank you kind sir! I only knew that calling a char array is the only way to generate a string since string is not a first-class variable in that you had shed some light for me and my program works perfectly fine now! Thank you soooo much!

Report •
Related Solutions

Ask Question