0

Just learning about call by reference. It's a basic program:

  1. I've a null pointer array A & array_size initlized to 0
  2. I've a function arrayInput(...) with arguments *A & *array_size
  3. Goal of this function is to store size input from user to array_size & then allocate that size to the above array.
void arrayInput(int *A, int *size) {
    printf("Enter the size of the array: ");
    scanf("%d", size);

    // allocate size to A
    A = (int*)malloc(sizeof(int)*(*size));  
}

int main(int argc, char **argv) {
    int *A, array_size = 0; // pointer array since I want to allocate the size later
    arrayInput(A , &array_size);
    
    printf("%d, %d", array_size, sizeof(A));
    return 0;
}

Actual Output:

Enter the size of the array: 5
5, 8

Expected Output:

Enter the size of the array: 5
5, 20

So why isn't it allocating memory to the array?

  • 2
    Also `sizeof(A)` is `sizeof(int*)` - which is determined at compile time. You cannot use `sizeof` to find out the size of a pointed to array – UnholySheep Nov 25 '22 at 15:24
  • @3rdgrade-dropout, `arrayInput(A , &array_size);` passes a copy of the value of `A` to `arrayInput()` - which is itself trouble because `A` has not yet been assigned. Anything `arrayInput()` does does not change `main()`'s `A`. Instead, pass the _address_ of `A`, so `arrayInput()` has a place to put the value of the allocated pointer. – chux - Reinstate Monica Nov 25 '22 at 16:14

0 Answers0