1

What is the difference between initialising character array as this

char c[10]={0};

and this

char c[10]="";

6
  • Consider using std::string for strings if possible. And NULL has a different meaning than 0 Commented Apr 23, 2020 at 11:06
  • 2
    which language? Tag says C++ and title says C... Commented Apr 23, 2020 at 11:07
  • 1
    @Timo: OP gets away with this by the skin of their teeth - answer is the same in either language. Commented Apr 23, 2020 at 11:07
  • @Bathsheba yeah but I don't know that because I don't know the C specification :P Commented Apr 23, 2020 at 11:08
  • 3
    @Timo: Does anyone? -;) Commented Apr 23, 2020 at 11:08

1 Answer 1

7

char c[10]={0}; guarantees that every element of the array is 0. Note that in C++ you can write char c[10]={}; which has the same effect.

char c[10]=""; guarantees that only the first element of the array is 0; the other elements are uninitialised.

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

3 Comments

Is there a way to see the difference while printing? for (int i=0;i<10;i++){ if(c[i]=='\0') printf("null char"); printf("%c\n",c[i]); } when I print this way both give same output
@PragatiSharma: That's the beauty of reading uninitialised char data: you don't know what you're going to get.
Okay, so be it.Thank you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.