2015-06-17 3 views
4

Самостоятельно ссылочная структура определена следующим образом:самосправочные структуры

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 in struct is 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

So data1 занимает 4 байта памяти, в котором целое число v довольный, верно?

Но почему в первом случае пространство памяти, занимаемое data1, увеличилось?

EDIT: В первом случае о/р

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

Можете ли вы сказать, какую версию системы и компилятора вы используете? –

+0

@Charles Я использую gcc-компилятор и версию gcc (GCC) 4.1.2 –

+0

На какой платформе? –

ответ

1

Struct padding - причина разницы, которую вы наблюдаете.

Я думаю, что вы находитесь на 64-битных системах, где размер указателя составляет 8 байтов (в структуре с указателем). Таким образом, компилятор выравнивает все три элемента до 8-байтового выравнивания. Но в более позднем случае это всего лишь два int, поэтому он выровнен до 4 байтов.

+2

Читайте здесь для получения другого объяснения: http://www.catb.org/esr/structure-packing/ –

+0

Если компилятор может выровнять границы 'int' с 4 байтами в этой системе, все равно имеет смысл поставить два' int 'в один 8-байтовый блок и указатель в соседнем 8-байтовом блоке, хотя? –

+0

@CharlesBailey То, что вы говорите, имеет смысл. Но я не знаю, почему. Возможно, OP может обновить адрес элемента-указателя в struct, 'sizeof', как структуры, так и детали платформы, которые точно объяснят, что происходит. –

Смежные вопросы