Arrays in C - Cprogramming.com
Let's look at something new here: the scanf function call is a tad different from what we've seen before. First of all, the format string is '%s' instead of '%d'; this just tells scanf to read in a string instead of an integer. Second, we don't use the ampersand! It turns out that when we pass arrays into functions, the compiler automatically converts the array into a pointer to the first element of the array. In short, the array without any brackets will act like a pointer. So we just pass the array directly into scanf without using the ampersand and it works perfectly.
I tried this with integers instead of string to try understanding what's happening internally.
Code:
#include <stdio.h>
int main( int argc, char *argv[] ) {
int scores[3] = {0,0,0};
printf("\n\nYour scores: ");
scanf("%d %d %d", scores, scores, scores);
printf("Your scores are: %d %d %d\n\n", scores[0], scores[1], scores[2]);
return 0;
}
Output:
Your scores: 11 14 20
Your scores are: 20 0 0
Code:
printf("Your scores are: %d %d %d\n\n", scores[0], scores[1], scores[2]);
If I remove the brackets [], I get addresses! So, I use "dereferencing" (*) and the output is suddenly 20 20 20.