Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an array terminate?

Tags:

c

As we know a string terminates with '\0'. It's because to know the compiler that string ended, or to secure from garbage values.

But how does an array terminate? If '\0' is used it will take it as 0 a valid integer, So how does the compiler knows the array ended?

like image 573
5war00p Avatar asked Dec 17 '22 16:12

5war00p


1 Answers

C does not perform bounds checking on arrays. That's part of what makes it fast. However that also means it's up to you to ensure you don't read or write past the end of an array. So the language will allow you to do something like this:

int arr[5];
arr[10] = 4;

But if you do, you invoke undefined behavior. So you need to keep track of how large an array is yourself and ensure you don't go past the end.

Note that this also applies to character arrays, which can be treated as a string if it contains a sequence of characters terminated by a null byte. So this is a string:

char str[10] = "hello";

And so is this:

char str[5] = { 'h', 'i', 0, 0, 0 };

But this is not:

char str[5] = "hello";  // no space for the null terminator.
like image 149
dbush Avatar answered Dec 31 '22 02:12

dbush