自我引用结构的定义如下:
对于第二种情况:
struct node{
int data1;
int data2;
struct node *ptr;
}obj,*temp;
int main()
{
printf("\n Address of variable data1 in struct is %p",&obj.data1);
printf("\n Address of variable data2 in struct is %p",&obj.data2);
}
输出结果为:
结构体中变量 data1 的地址是 0xd0c7010
结构体中变量 data2 的地址是 0xd0c7018
这意味着 data1
占用了 8 字节的内存,对吗?
但如果我有以下结构体定义:
struct node{
int data1;
int data2;
}obj,*temp;
int main()
{
printf("\n Address of variable data1 in struct is %p",&obj.data1);
printf("\n Address of variable data2 in struct is %p",&obj.data2);
}
输出结果为:
结构体中变量 data1 的地址为 0xd0c6010
结构体中变量 data2 的地址为 0xd0c6014
因此,data1
占用的内存空间为 4 字节,就像整数变量一样,对吗?
但是,在第一种情况下,为什么 data1
占用的内存空间增加了呢?
编辑: 对于第一种情况,输出结果为
Address of variable data1 in struct is 0x600940
Address of variable data2 in struct is 0x600944
The address of ptr is 0x600948
The size of struct is 16
对于第二种情况:
Address of variable data1 in struct is 0x600910
Address of variable data2 in struct is 0x600914
The size of struct is 8
我正在Linux上使用gcc (GCC) 4.1.2运行此代码
上述代码可以正常工作,但下面这个呢?
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
// This function prints contents of linked list starting from the given node
void printList(struct node *n)
{
printf("\n The memory location of n is %p ",n);
while (n != NULL)
{
printf(" %d ", n->data);
n = n->next;
printf("\n The memory location of n in while loop is %p ",n);
}
}
int main()
{
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
// allocate 3 nodes in the heap
head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));
head->data = 1; //assign data in first node
head->next = second; // Link first node with the second node
printf("\n The memory address of head->data is %p ",&head->data);
printf("\n The memory address of head->next is %p ",&head->next);
second->data = 2; //assign data to second node
second->next = third;
printf("\n The memory address of second->data is %p ",&second->data);
printf("\n The memory address of second->next is %p ",&second->next);
third->data = 3; //assign data to third node
third->next = NULL;
printf("\n The memory address of third->data is %p ",&third->data);
printf("\n The memory address of third->next is %p ",&third->next);
printList(head);
getchar();
printf("\n");
return 0;
}
O/P是指
The memory address of head->data is 0x215c010
The memory address of head->next is 0x215c018
The memory address of second->data is 0x215c030
The memory address of second->next is 0x215c038
The memory address of third->data is 0x215c050
The memory address of third->next is 0x215c058
The memory location of n is 0x215c010 1
The memory location of n in while loop is 0x215c030 2
The memory location of n in while loop is 0x215c050 3
The memory location of n in while loop is (nil)
为什么现在还有8个字节的差异? 我正在与其他两个相同的环境下运行此代码。