-1

I am writing a c++ function to calculate the size of an C-type array in C++

I noticed a very strange behavior when using these two different codes:

code 1:

int sz = sizeof array / sizeof *array;

code 2:

int array_size(const int *pointer)
 {   int count=0;
    if(pointer)
        while(*pointer) {
            count++;
            pointer++;
        }
    return count;

 }

When I applied these two method on a array, it gave me very strange behavior:

example 1 :

int array[10] = {31,24,65,32,14,5};// defined to be size 10 but init with size 6

the code one will give me size = 10, but code 2 will give me size 6,and when I print out the element that is pointed by *pointer, it will give me the correct array elements:

31 24 65 32 14 5

example 2

int array[] = {31,24,65,32,14,5}; // no declared size but init with 6

Code 1 will give me size 6, code 2 will give me size 12, and when I print out the element that is pointed by *pointer in code 2, it gives me :

31 24 65 32 14 5 -802013403 -150942493 1461458784 32767 -1918962231 32767 

which is really not right, so what could be the problem that cause this behavior? and what are those numbers?

Thanks for your answer

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Chrim
  • 100
  • 8

3 Answers3

6

This array has 10 elements, regardless of how you initialize it:

int array[10] = {31,24,65,32,14,5};

But the initialization sets the first 6 elements to certain values, and the rest to 0. It is equivalent to this:

int array[10] = {31,24,65,32,14,5,0,0,0,0};

The first calculation using sizeof uses the actual size fo the array (its length times the size of an int), while the second one counts elements until it finds a 0. So it doesn't calculate the length of the array, but the length of the first non-zero sequence in the array.

Note that the second method only "works" if the array has an element with value 0. Otherwise you go out of bounds and invoke undefined behaviour.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Thanks very much, So does that mean when the array size is not defined, a pointer that points to the array will eventually go out of bound and will give me strange value ? – Chrim May 30 '15 at 16:51
  • @Chrim The array size is defined. Its length is 10. But a pointer is a pointer. You can't get the length of an array from a pointer to an element of the array (i.e. if an `int*` points to an element of an `int[42]`, there's no way you can get the `42` from the pointer.) – juanchopanza May 30 '15 at 16:56
  • Thanks , This is really helpful. – Chrim May 30 '15 at 17:03
2

array_size assumes that there is a 0 just past the end of the array. That assumption is unjustified.

Oswald
  • 31,254
  • 3
  • 43
  • 68
1

code 2 is not right. you can't assume an array end with 0

Xiaotian Pei
  • 3,210
  • 21
  • 40