-2

This is my code:

int main() {
    int i,n, *arr;
    scanf("%d", &n);
    arr = (int *)malloc(sizeof(int)*n);
    for(i = 0; i < n; i++)
        scanf("%d", &arr[i]);
    printf("%lld", sumOfArray(arr,n));

    return 0;
}

Why do I have to use &arr[i]? I thought that it's not needed when arr is of type int *.

Tlacenka
  • 520
  • 9
  • 15

3 Answers3

1

scanf() takes a memory address, which it resolves to a pointer to push data to; arr on its own would be a pointer, but arr[i] is an int. Therefore, you need to pass the address of arr[i] to scanf()

F. Stephen Q
  • 4,208
  • 1
  • 19
  • 42
1

Although arr is of type int *, that's not where scanf is putting the data. It's putting it in arr[i], which is of type int. Therefore, you need to pass the address of that variable, i.e. &arr[i].

dbush
  • 205,898
  • 23
  • 218
  • 273
1

Use & to get the address of an object.

Which of these makes sense?

scanf("%d", ... needs an address of an int as the next argument.


&n is an int *. Good

int n;
scanf("%d", &n);

arr is an int *. Good.

int *arr = malloc(1 * sizeof(*arr));
scanf("%d", arr);

arr[i] is an int: Bad

int *arr = malloc(n * sizeof(*arr));
for(i = 0; i < n; i++)
    scanf("%d", arr[i]); // bad

&arr[i] is an int *: Good

int *arr = malloc(n * sizeof(*arr));
for(i = 0; i < n; i++)
    scanf("%d", &arr[i]);

&arr[i] is an int *: Good

int arr[5];
for(i = 0; i < 5; i++)
    scanf("%d", &arr[i]);

arr is an "array 1 of int". Because it is an array, when passed to a function, arr is converted to the address of its first element. This is an int *: Good

int arr[1];
scanf("%d", arr);

&arr is the address of an "array 1 of int". Although this has the same value as &arr[0], it is not an int *: Bad

int arr[1];
scanf("%d", &arr); // Bad

Result scanf("%d", ... needs an int * argument.

  1. When the modifiable object being passed converts to an int, an & is needed.

  2. When the object being passed converts to an int *, no & is needed.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256