I have been learning C, and coming from more high level languages it definitely is something new! I know that arrays are terminated by a '\0'
value, and I was wondering what are the instances in which the compiler does not provide this? For example:
int main() {
int val;
scanf("%d", &val);
char arr[val + 1];
arr[val] = '\0'; // The null value must be stated or something unpredictable occurs
for (int i = 0; i < val; i++ ) {
arr[i] = 'a';
}
printf("This is the output:\n%s", arr);
char arr2[5]; // This works perfectly fine
for (int i = 0; i < 5; i++ ) {
arr2[i] = 'a';
}
printf("This is the output:\n%s", arr2);
}
So the concept I have been getting is that when we either
- Dynamically allocate memory or
- Don't know the size of an array at compile time
is when the compiler can't/doesn't supply the ending null value. If this is the case, are there other cases to be aware of when working with arrays?
EDIT: After being pointed out, arr2
in this sense is not provided an ending zero terminator although it prints what I would expect.