Why did the array lose the last element when passed into another function?

Viewed 30

I made an static int arr[3] and set to 1, 2, 3.

I can print 1, 2, 3 in the same function.

But when I pass the array it only prints 1, 2.

Why? What happened? How do I fix this?

#include <stdio.h>

void printArray(int* arr){
size_t n = sizeof(arr)/sizeof(arr[0]);
  for(int i=0; i<n; i++){
    printf("%d\n",arr[i]);
  }
}

int* makearray()
{
        static int arr[3];
        arr[0] = 1;
        arr[1] = 2;
        arr[2] = 3;

        printf("The Array before passing onto stack\n");
        size_t n = sizeof(arr)/sizeof(arr[0]);
        for(int i=0; i<n; i++){ printf("%d\n",arr[i]);}

        printf("\nThe Array when attempting to pass to another function\n");
        printArray(arr);
        return arr;
}
int main(void) {

  int* m = makearray();

  return 0;
}
1 Answers

By converting your array to a pointer, you removed the information that sizeof needs to know its total length.

Instead, it just gives you the size of a single int *, which is twice the size of a single int on your machine.

Hence, you only see the first two elements.

In C, you're basically forced to pass around the length alongside the pointer. You can wrap the two in a struct to make it easier to use, but don't expect the niceties of other languages you may be used to.

Related