Search code examples
cpointersdynamic-memory-allocation

I don't understand why we put the "&" in the scanf with ageAmis while ageAmis is a pointer?


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;

}


Solution

  • 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]