d0rmLife
d0rmLife

Reputation: 4240

C: surprising array result

Apparently C doesn't like the declaration:

char some_array[n] = "Text here"; <== where n is an int of suitable size....

Well, actually, I guess it likes it just fine, but the output surprises me! Here's an example.

    char two[4] = "What";
    printf("2: %s \n", two);

Output is:

2: WhatWhat 

WhatWhat the heck is WhatWhat doing there?!

So I try adding:

    char test[4] = "abcd";

Output is:

2: WhatWhatabcd
3: abcd

Yeah, I get it, my syntax isn't favored. But why?! And what is going on with the actual variables?

Upvotes: 0

Views: 94

Answers (4)

Kinjal Patel
Kinjal Patel

Reputation: 405

because your max array index is 4, you are facing this problem.

make the max array index to 5, e.g. char test[5] so that it can terminate the string with NULL. your problem will be sorted.

Upvotes: 1

Anshul
Anshul

Reputation: 1436

A string is terminated by only a NULL character, in your case since you have allocated a space of 4 bytes and you are storing "what" in it exactly 4 characters so there is no space left for NULL termination.

While printing printf starts to read the data from the starting address that you mention and goes till NULL character... So its possible that the adjacent memory where the buffer is allocated have some junk characters(since memory is not flushed automatically, in all cases ,when the buffer is freed) so you are seeing whatwhat or it might be whatjkefwhksdjfsdfjsf some other day... or possibly a segmentation fault if it goes to read till an unauthorized location of memory.

Upvotes: 1

Jay
Jay

Reputation: 24895

While dealing with strings you should take the null terminator into consideration. Here you are trying assign a string literal of 4 characters to an array of 4 characters, thereby not providing an extra character space for the null terminator.

change the code as below:

char two[5] = "What";
char test[4] = "abcd";

As to why for "What" you are having the problem and not having it for "abcd", the behavior will be undefined for such cases, as the program will try to search the memory till a null terminator is found. In your case, it is printing incorrect, it can lead to a crash, hang or god knows what.

Upvotes: 1

Pubby
Pubby

Reputation: 53017

String literals have an extra character - the nul terminator.

So you need to have it be length 5:

char two[5] = "What";

Or this if possible:

char two[] = "What";

(you're getting a buffer overrun or something otherwise)

Upvotes: 3

Related Questions