C - why is & needed for char array scan but not int? [duplicate]
The scanf
function expects a pointer. The &
operator gets the address of a variable. When passed to a function, any array (including char
arrays) decays to a pointer to its first element, so the &
operator is unnecessary.
This can be seen in the below very simple program that prints an array of ints.
#include <stdio.h>
void print(int *arr, size_t n) {
for (size_t i = 0; i < n; ++i) {
printf("%d\n", arr[i]);
}
}
int main(void) {
int arr[] = {1, 2, 3, 4, 6, 7, 8, 9};
print(arr, 8);
return 0;
}
The print
function expects an array of ints. The array arr
is passed in and decays to a pointer to the first element.