1

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;
}
mhluo132
  • 11
  • 1
  • 1
    This is a common beginner's mistake. C doesn't automatically pass the size of an array along with its address. It just passes a pointer to the array. Look at the declaration of `arr` in `printArray`. It's a pointer, right? So `sizeof(arr)` will be the size of a pointer, not the size of the array. – Tom Karzes Nov 06 '21 at 23:38

1 Answers1

1

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.

Alexander
  • 59,041
  • 12
  • 98
  • 151