ShadyBears
ShadyBears

Reputation: 4185

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?
}

Upvotes: 3

Views: 3350

Answers (4)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

When you declare char word1[20]; creates an array of 20 chars. Here, word1 is the address of its first element but not of the array.

& word1 means address of array. The values of word1 and &word1 are really the same, but semantically both are different. One is an address of a char, while the other is an address of an array of 20 chars. you should read this answer.

second case:

when you declare char *word2; you creates a pointer variable. it can point to a char or can store address of dynamically allocated array like you did.

so value of word2 means address return by malloc(). in below line.

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

but expression &word2 means address of pointer variable. and address return by malloc is different then address of pointer veritable word2.

word2 is not same as word1 type.

read also Nate Chandler's answer

The fundamental difference between word1 and word2:

In below diagram.

diagram

word1 is same as a (not by size but by type). and word2 is like p

here value of p means address of "world" string and &p means address of p variable.

Upvotes: 2

Ganesh
Ganesh

Reputation: 5980

In the first statement &word1 refers to the address of the array. Since this array is statically allocated on stack &word1 is same as word1 which is same as &word1[0].

In the second case word2is pointer on stack whose address is shown in first part of print and word2 contains the pointer which is allocated through malloc.

Upvotes: 0

Michael Dorgan
Michael Dorgan

Reputation: 12515

The first is the address on the stack of the word2 pointer - a double pointer where the value is stored.

The second is the actual address stored within word2 - somewhere on the heap I would presume from the malloc.

Upvotes: 2

Steve Jessop
Steve Jessop

Reputation: 279245

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

&word2 is the address of the variable named word2.

Upvotes: 7

Related Questions