自引用结构的定义如下:
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);
}
o / p是
struct中变量data1的地址为0xd0c7010
struct中变量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);
}
o / p是
struct中变量data1的地址为0xd0c6010
struct中变量data2的地址为0xd0c6014
所以data1
占用4个字节的内存,这是一个整数变量,对吗?
但是为什么第一种情况是data1
占用的内存空间增加了?
编辑: 对于第一种情况,o / p是
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个字节的差异? 我在与其他两个相同的环境下运行此代码。
答案 0 :(得分:1)
Struct padding是您观察到差异的原因。
我认为你是64位系统,指针大小为8字节(在带指针的结构中)。因此编译器将所有三个成员对齐为8字节对齐。但在后一种情况下,它只有两个int
,因此它与4个字节对齐。