3

在 main 函数的最后一行,为什么与&word2不同word2?假设正确的标题就位。谢谢!

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

4 回答 4

7

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

&word2 is the address of the variable named word2.

于 2013-02-12T16:59:53.783 回答
2

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.

于 2013-02-12T17:00:07.460 回答
2

当您声明char word1[20]; 创建一个包含 20 个字符的数组时。这里,word1是它的第一个元素的地址,而不是数组的地址。

& word1表示数组的地址。word1和的值 &word1实际上是相同的,但在语义上两者是不同的。一个是 char 的地址,而另一个是 20 个字符的数组的地址。你应该阅读这个答案

第二种情况:

当您声明时, char *word2;您会创建一个指针变量。它可以指向一个字符,也可以像你一样存储动态分配的数组的地址。

所以值word2意味着地址返回malloc()。在下一行。

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

但表达式&word2表示指针变量的地址。并且 malloc 返回的地址与指针 veritable 的地址不同word2

word2word1类型不同。

另请阅读Nate Chandler 的回答

word1 和之间的根本区别word2

在下图中。

图表

word1a不是按大小而是按类型)相同。word2就像_p

这里的值p表示"world"字符串的地址,表示变量的&p地址。p

于 2013-02-12T17:08:40.870 回答
0

在第一条语句&word1中指的是数组的地址。&word1由于该数组是在堆栈上静态分配的word1,因此与&word1[0].

在第二种情况下word2是堆栈上的指针,其地址显示在 print 的第一部分,并word2包含通过 分配的指针malloc

于 2013-02-12T17:08:37.963 回答