链表基本内存(C语言)
Linked list basic memory(in C)
我试图更好地理解链表中的内存是如何分配的,所以我编写了一个简单的程序来查看地址的存储位置。
#include <stdio.h>
struct node {
int data;
struct node* next;
};
int main()
{
struct node first;
struct node second;
struct node third;
struct node *aux; //pointer to go through list
first.data = 1;
second.data = 2;
third.data = 3;
first.next = &second;
second.next = &third;
third.next = NULL;
aux = &first;
while (aux)
{
printf("%p\n", aux); //printing each address
aux = aux->next;
}
return 0;
}
我们得到输出:
0x7fff14fabac0
0x7fff14fabad0
0x7fff14fabae0
所以节点之间有1个字节的差异。
所以基本上 first = second - 1。既然 sizeof(int) 等于 4 个字节,为什么内存中还有空间留给整数,而我们只前进 1 个字节?
您忽略了最后一位,相差 16 个字节。 16 个字节很可能是您的系统 8 字节对齐的结果。
我试图更好地理解链表中的内存是如何分配的,所以我编写了一个简单的程序来查看地址的存储位置。
#include <stdio.h>
struct node {
int data;
struct node* next;
};
int main()
{
struct node first;
struct node second;
struct node third;
struct node *aux; //pointer to go through list
first.data = 1;
second.data = 2;
third.data = 3;
first.next = &second;
second.next = &third;
third.next = NULL;
aux = &first;
while (aux)
{
printf("%p\n", aux); //printing each address
aux = aux->next;
}
return 0;
}
我们得到输出:
0x7fff14fabac0
0x7fff14fabad0
0x7fff14fabae0
所以节点之间有1个字节的差异。
所以基本上 first = second - 1。既然 sizeof(int) 等于 4 个字节,为什么内存中还有空间留给整数,而我们只前进 1 个字节?
您忽略了最后一位,相差 16 个字节。 16 个字节很可能是您的系统 8 字节对齐的结果。