0

That's the code: I don't understand why we put the "&" in the scanf with ageAmis while ageAmis is a pointer? NB "This code works"

int main(int argc, char *argv[]){
int nombreDAmis = 0, i = 0;
int* ageAmis = NULL; // Ce pointeur va servir de tableau après l'appel du malloc

// On demande le nombre d'amis à l'utilisateur
printf("Combien d'amis avez-vous ? ");
scanf("%d", &nombreDAmis);


    ageAmis = malloc(nombreDAmis * sizeof(int)); // On alloue de la mémoire pour le tableau


    // On demande l'âge des amis un à un
    for (i = 0 ; i < nombreDAmis ; i++)
    {
        printf("Quel age a l'ami numero %d ? ", i + 1);
        scanf("%d", &ageAmis[i]); //why the "&"
    }

    // On affiche les âges stockés un à un
    printf("\n\nVos amis ont les ages suivants :\n");
    for (i = 0 ; i < nombreDAmis ; i++)
    {
        printf("%d ans\n", ageAmis[i]);
    }

    // On libère la mémoire allouée avec malloc, on n'en a plus besoin
    free(ageAmis);
}

return 0;

}

Youssef Khedher
  • 106
  • 1
  • 11
  • 3
    Because `ageAmis[i]` is a value (as passed to `printf`), and `&ageAmis[i]` is its location, so that it can be altered by `scanf`. – Weather Vane Feb 14 '19 at 22:21
  • 2
    _ageAmis_ is a pointer but _ageAmis[i]_ is not apointer but an _int_, so you have to give the address (&) for _ageAmis[i]_ exactly like you did for _nombreDAmis_ – bruno Feb 14 '19 at 22:27

1 Answers1

2

You are right that ageAmis is a pointer. However, that's not what you pass to scanf().

ageAmis[i] has type int because you are dereferencing i location from ageAmis base address. It's equivalent to *(ageAmis + i). That's you can't pass ageAmis[i] to scanf as it expects an argument of type int* for the format %d. So & is required here.

You could alternatively just pass ageAmis + i as well:

    scanf("%d", ageAmis + i);

which is equivalent to:

    scanf("%d", &ageAmis[i]);

Note that:

*(ageAmis + i) == *(i + ageAmis) == ageAmis[i]
P.P
  • 117,907
  • 20
  • 175
  • 238