TADASUKE
TADASUKE

Reputation: 115

C Programming: Why Can This Sample Line Have Not '0' OR '\0' Character At The End Of The Array?

I am still a C programming newbie.

I have heard the character string has always '0' or '\0' as the final character.

Then I have a one question. why the sample line below has '5' at the last position?

Why isn't it '0' or '\0'?

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };

The line above from How to initialize all members of an array to the same value?

Upvotes: 1

Views: 231

Answers (3)

"Why can this sample line have not 0 OR '\0' character at the end of the array?"

Because myArray is an array of int (and does not contain a string)! A null terminator (for strings) can only be applied to char, but not int arrays.

And even an array of char does not a null terminator per se. Only if the array of char should contain a string and you want to use the content of the array as string, a null terminator is required.

Beside that, an array of int can of course hold the int value 0 inside of the last element but you currently intermix two different things here.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

Strings are character arrays the actual elements of which are terminated by zero character. And most standard C string functions relay on this convention.

This

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };

is an integer array. Zero is a valid integer value. And it is used very often as an actual value of an array among other integer values.

Of course you can make zero a sentinel value of an integer array. But there are no standard C functions that use zero as a sentinel value for integer arrays.

Upvotes: 2

ssd
ssd

Reputation: 2422

char cArr1[] = {'a', 'b', 'c'};
char cArr2[] = "def";
int iArr3[] = {1, 2, 3};
int iArr4[5] = {1, 2, 3};

memory layout
=============
var name    memory address    value
cArr1       AAAA0000          'a'
            AAAA0001          'b'
            AAAA0002          'c'
            AAAA0003          unknown (may have a '\0' by chance)
            ...
cArr2       BBBB0000          'd'
            BBBB0001          'e'
            BBBB0002          'f'
            BBBB0003          '\0' is inserted by the compiler
            ...
iArr3       CCCC0000          1
            CCCC0004          2
            CCCC0008          3
            CCCC000C          unknown (may have any value)
            ...
iArr4       DDDD0000          1
            DDDD0004          2
            DDDD0008          3
            DDDD000C          0 (not defined explicitly; initialized to 0)
            DDDD0010          0 (not defined explicitly; initialized to 0)
            ...

Upvotes: 5

Related Questions