Why don't we use the backslash zero in integer arrays to save memory or prevent overflow like character arrays or strings?
3 Answers
if we add \ 0 at the end of an array of integers, this array will be treated as a string and each element as a character, you note that C is a strongly typed language, the difference between '4' and 4 integer can have unintended consequences in your program.
In addition to what @MARS said: Unlike a string (array of charts or string literal), an integer must and will always be 4 bytes, whereas a string can be of any length. The implications of this is then, in a string the compiler must read every byte until a '\0' is found, but in an integer the compiler knows that the integer occupies the next four bytes including the current, therefore it can "jump" four bytes to the end.
Another way to look at it is
Terminating some memory with a '\0' is explicit. I,e, the string ends here.
Memory that the compiler knows to be an integer (or any item of constant size) is terminated implicitly. I,e, the string must end here.
Edit I also want to mention there is no such thing as an integer array. An integer is a single unit, or one block of bytes. It is not possible to index it, for example you can't say int a = 1; char b = a[2];
A string
is an array of char
(which is 1 byte). And as a string
can have any length (or any number of char
), we use the '\0'
to represent the end of a string (the next char/byte
right after the last char
of a string).
Now let get to your question:
A int
is a data type stored in 4 bytes. And '\0'
, which again is 1 byte, is defined to be a null character - that is a character with all bits set to zero.
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type.
All arrays consist of contiguous memory locations.
If you are talking about making "dynamic array size" in C, the solution is to use a linked list. You learn about linked list in CS50 in the middle of the class.
Why do you mean by 'to save memory'?
DON'T FORGET TO UPVOTE OR MARK AS SOLUTION