Static char array declaration in C

Can someone explain to me why it int array[3] = {1,2,3}

works but char array[3] = "123"

doesn't work?

He typed "123 ((" instead of "123").

The char array is said to require a different null character space, but it doesn't start at 0, so that's char array[3]

enough since it's actually 4 spaces. Where the char array actually requires 2 spaces for null and one for special character.

+3


source to share


2 answers


int array[3] = {1,2,3}

      

allocates an array that can contain at most 3 integers, and you can access any of them using the following methods:

array[0]
array[1]
array[2]

      

Here:

char array[3] = "123"

      

"123"

consists of 4 bytes. Characters in a string literal are terminated with a NUL terminator. But you allocate 3 bytes and can hold 2 characters (+1 for a NUL terminator). So when you initialize the array with it, it is '\0'

not written as there is no room.

When you print this using %s

in printf

, it invokes Undefined behavior as it %s

prints everything as long as the NUL terminator. Therefore, it printf

continues to read values ​​from invalid memory locations until '\0'

. Anything can happen when you do. You may see random garbage dumps, crashes, segmentation errors, etc. Basically, you should never rely on this behavior, even if it seemed to "work" as expected.

but doesn't start an array of 0

Yes

so char array[3]

enough, since it is actually 4 spaces



Wrong. Valid indices for char array[3]

are

array[0]
array[1]
array[2]

      

access is array[3]

invalid and calls Undefined Behavior .


Fix the problem using

char array[4] = "123";

      

or better:

char array[] = "123";

      

The empty parentheses tell the compiler to determine the size of the array.

+6


source


When you declare an array in c, the char [3] array will give 3 characters, not 4 as you said in your question. In this case, you need space for the null character at the end of the string, so you need a char [4] array.



+3


source







All Articles