Search code examples
cc-stringsdynamic-allocation

Memory address in C


In the last line of the main function, why does &word2 differ from word2? Assume the right headers are in place. Thank you!

int main()
{
    char word1[20];
    char *word2;

    word2 = (char*)malloc(sizeof(char)*20);

    printf("Sizeof word 1: %d\n", sizeof (word1));
    printf("Sizeof word 2: %d\n", sizeof (word2));

    strcpy(word1, "string number 1");
    strcpy(word2, "string number 2");

    printf("%s\n", word1);
    printf("%s\n", word2);
    printf("Address %d, evaluated expression: %d\n", &word1, word1);
    printf("Address %d, evaluated expression: %d\n", &word2, word2); 
    //Why this one differ?
}

Solution

  • word2 is the address of the memory that you allocated using malloc.

    &word2 is the address of the variable named word2.