Memory address in C

On the last line of the main function, why &word2

is it different from word2

? Let's assume the correct headers are set. Thank!

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

      

+3


source to share


4 answers


word2

is the address of the memory that you allocated with malloc

.



&word2

is the address of a named variable word2

.

+7


source


The first is the address on the pointer stack word2

- a double pointer that stores the value.



The second is the actual address stored in word2

- somewhere on the heap, which I would guess from malloc.

+2


source


When you declare char word1[20];

, a 20 character array is created. Here word1

is the address of its first element, but not an array.

& word1

means the address of the array. Values word1

and &word1

in fact are the same, but both are semantically different. One is a char address and the other is a 20 character array address. you should read this answer .

second case:

when you declare char *word2;

, you create a pointer variable. it can point to char or it can store the address of a dynamically allocated array as you did.

so the value word2

means returning the address to malloc()

. on the bottom line.

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

      

but the expression &word2

means the address of the pointer variable. and the return by malloc address is different from the pointer address word2

.

word2

does not match the type word1

.

read also Nate Chandler's answer

The main difference between word1

and word2

:

At the bottom of the diagram.

diagram

word1

matches a

(not in size, but in type). and is word2

likep

here value p

means string address "world"

and &p

means variable address p

.

+2


source


The first statement &word1

refers to the address of the array. Since this array is statically allocated on the stack &word1

, the same as word1

, which is the same as &word1[0]

.

In the second case, it word2

is a pointer to the stack, the address of which is shown in the first part of the print, and word2

contains a pointer that is allocated through malloc

.

0


source







All Articles