我从这个link得到了一个小程序,该程序将元素压入堆栈。仔细检查后,我发现程序中该下一个指针为第一个值,第二个值和第三个值占用的存储空间价值是不同的。谁能给我令人满意的解释,为什么会这样。
我正在使用gcc编译器
#include <stdlib.h>
#include <stdio.h>
struct Node
{
int data;
struct Node *next;
};
int push_front( struct Node **head, int data )
{
struct Node *tmp = malloc( sizeof( struct Node ) );
int success = tmp != NULL;
if ( success )
{
tmp->data = data;
tmp->next = *head;
*head = tmp;
printf("\nAddress of pointer head now is %p for value %d",*head,data);
}
return success;
}
int main( void )
{
struct Node *head;
for ( int i = 0; i != 10; i++ ) push_front( &head, i );
return 0;
}
=======================================================================
output
-----
Address of pointer head now is 0x16f1010 for value 0
Address of pointer head now is 0x16f1440 for value 1
Address of pointer head now is 0x16f1460 for value 2
Address of pointer head now is 0x16f1480 for value 3
Address of pointer head now is 0x16f14a0 for value 4
Address of pointer head now is 0x16f14c0 for value 5
Address of pointer head now is 0x16f14e0 for value 6
Address of pointer head now is 0x16f1500 for value 7
Address of pointer head now is 0x16f1520 for value 8
Address of pointer head now is 0x16f1540 for value 9
期望这样,以便在插入每个值时标头指针应占用相等的地址空间字节。
答案 0 :(得分:1)
malloc
用于动态分配给定大小的连续块。此内存是从堆分配的。
malloc
不保证两次连续调用malloc
之间分配的内存是连续。