ivanb ivanb - 1 month ago 6
C Question

c lang - different array length by pointer

I have problem with my own function for get array length.
Code:

#include <stdio.h>
int main() {
int a[] = {5,4,1,2,1}; //len -> 6!! FAIL! WHY?
//int a[] = {5,4,1,2}; //len -> 4 OK!
int len = 0;
int *p = a;
while(*p != '\0'){
printf("%d\n", *p);
len++;
*p++;
}
printf("len: %d\n", len);
return 0;
}


code above output:

5
4
1
2
1
32767
len: 6


but this array int a[] = {5,4,1,2}; - produce len = 4 - ok.

why it happens?

Answer

It fails because there's no 0 at the end of your array. It's not added automatically, you need to do it explicitly. As a result, you accessed outside the array, which results in undefined behavior. The fact that one of your tests seemed to work was purely luck, you can't depend on it.

int a[] = {5, 4, 1, 2, 1, 0};

The only time that C automatically adds a null terminator is when you use a string literal to initialize a char array, e.g.

char c[] = "abcde";
Comments