1

There is a null character at the end of a "string". But, is there a default NULL pointer at the end of a {brace initialization}?

I always do:

char *array[]={"AA", "BB"};

Someone asked me if the proper way is:

char *array[]={"AA", "BB", NULL};

I have no idea if I have been doing it right or wrong. Any clue?

  • All extra elements in the initialized array will be zero initialized but your first array has only 2 elements. – Antti Haapala -- Слава Україні Jul 05 '20 at 06:24
  • I have been told that there are similar answers to this question. But I have no idea what to do. Anyway, the answer is that I have been doing this wrong all this time by assuming that there is a NULL pointer terminator at the end. –  Jul 05 '20 at 07:11

2 Answers2

2

"AA" is indeed 'AA\0', two characters A and a '\0' (being a zero byte). Conventionally, in C and C++, writing "something" will automatically add a 0-byte after the characters of something. Thus the size in bytes of "something" is 10.

In the array, "AA" gives the address of the string "AA", and NULL gives an address zero (all bytes of an address are set to zero).

It is fine to define the array like

char *array[] = { "AA", "BB" };

Adding a NULL merely adds an item to the array, being a null-address (zero). But syntactically both are correct.

However, some functions (for instance from a library), might require to add a NULL after a list of values. To indicate this is the last argument (some functions of the exec family for instance, see this answer)

Déjà vu
  • 28,223
  • 6
  • 72
  • 100
2

There is not an implicit NULL pointer at the end of arrays.

Some APIs that take arrays of pointers expect the last element of the array to be NULL in lieu of passing a length of the array.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173