Is an array initialized from a string literal identical to one initialized from individual characters?

  • A+
Category:Languages

There are two arrays:

char a[] = "Nice you!";      char b[] = {'N', 'i', 'c', 'e', ' ', 'y', 'o', 'u', '!'}; 

I think a[] and b[] are exactly the same. So here's my code to see what is after the final element of each array:

#include <stdio.h>  int main(void) {     char a[] = "Nice you!";     char b[] = {'N', 'i', 'c', 'e', ' ', 'y', 'o', 'u', '!'};      char *pa;     char *pb;     pa = a;     pb = b;     printf("*(pa + 9)= %d/n", *(pa + 9));     printf("*(pb + 9)= %d/n", *(pb + 9));      return 0; } 

Is my understanding correct? I am not so sure and need confirmation.

 


It's almost the same.

This array is NUL terminated:

char a[] = "Nice you!"; 

This array is not NUL terminated:

char b[] = {'N', 'i', 'c', 'e', ' ', 'y', 'o', 'u', '!'}; 

The exact equivalent of array a is this:

char c[] = {'N', 'i', 'c', 'e', ' ', 'y', 'o', 'u', '!', 0};                                                          ^ NUL terminator 

In your code *(pb + 9) accesses one element beyond the array, therefore the behaviour of your program is undefined.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: