John Nash
John Nash

Reputation: 77

Array initialization in C

Can someone please explain me why its not possible to put a '\0' character in the given array:

char a[]={'r','b'};

a[2]='\0';

Shouldn't the above code put a null character at the third slot and hence convert the character array a to a character string.

Upvotes: 1

Views: 230

Answers (3)

lightalchemist
lightalchemist

Reputation: 10211

While TeoUltimus answer is correct, do note that the pointer 'a' in his case will pointing to a string literal. This means you can never modify the string. More specifically, while the code a[1] = 'c'; will compile, running it will lead to an error. Write char a[] = "ab" if you intend the individual elements in the string to be modified. For details see: https://www.securecoding.cert.org/confluence/display/seccode/STR30-C.+Do+not+attempt+to+modify+string+literals

Upvotes: 0

TEOUltimus
TEOUltimus

Reputation: 184

Strings in C are implemented as an array of characters and are terminated with a null '\0'. Just say char* a = "rb";. (Remember to include string.h)

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You are writing past the array boundary: when you initialize an array with two characters, the last valid index is 1, not 2.

You should initialize your array with three items, as follows:

char a[] = {'r', 'b', '\0'};

You could as well use this version:

char a[] = "rb";

This will give you a writable array with a zero-terminated string inside.

Upvotes: 7

Related Questions