string logical question

Jul 18, 2013 at 2:08pm
please see the following snippet. i get a garbage value as output.

void main()
{
char arr[7]="network";
printf("%s",arr);
}
Jul 18, 2013 at 2:27pm
I'm surprised it compiles. I get the following error.
error: initializer-string for array of chars is too long [-fpermissive]


"network" is 8 chars. 7 letters + a null character '\0' to mark the end of the string. If you change arr to size 8 it will probably work as you expected.
Jul 19, 2013 at 2:14pm
@peter87, whch compiler do you use?? i use turbo c++. i m getting wierd results. when i change the array size to six and hardcode it to "networ"
i get proper output as networ. i m confused.
Last edited on Jul 19, 2013 at 2:15pm
Jul 19, 2013 at 2:34pm
I use GCC.

I said you should change the size to 8. If you change the string to "networ" you should change the size to 7.

If you leave out the size the compiler will automatically make the array big enough to store the string.
 
char arr[]="network";


What your compiler seems to be doing is that if the array is shorter than the string it just ignores the characters that doesn't fit, so in your original code arr will contain all characters in "network" except for the last character, the null character. When you print the array it will go through the characters one by one and stop when it finds a null character. arr doesn't contain a null character so it just continue printing the bytes after the array, which is why you got garbage output.
Jul 19, 2013 at 2:40pm
i don't think you should get proper results.
a c-string must be 1 character longer than its content, this extra slot is used to contain the null terminator.
if your compiler doesn't care about this initialization and still compiles the program, and if you send the string to the output stream, you should get the phrase "network" followed by multiple garbage characters.
why is this behavior:
the output function keeps printing characters until it reaches a null character, which tells it to stop printing.
if your string doesn't contain such character, then you're on a date with your luck, you might eventually get an access violation error.
Jul 19, 2013 at 3:24pm
closed account (Dy7SLyTq)
try [] = "network"
Topic archived. No new replies allowed.