1

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.

2
  • You can take char a[3]={'r','b'}; and you have enough defined memory to put on a[2]. Commented May 19, 2012 at 11:25
  • John Nash asking such basic Question ? naaaahhhh.. /) Commented May 25, 2012 at 0:43

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, that makes sense. Thanks for the prompt reply.
Since I am new to this, can u help me locate the Accept button. Thanks.
@JohnNash There's an outline of check mark next to the answer.
Ok. I just clicked on that check mark and it turned green. I guess, that would mean that the answer has been accepted.
1

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)

Comments

0

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

1 Comment

Thanks, that certainly helped!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.