lh84
lh84

Reputation: 45

C++ Memory address in linked list and in array

I have simple program

struct Node
{
    int data;
    Node *next;
};

int main()
{
    // Make linked list with 10 Node
    Node* head = new Node();
    head->data = 9;
    Node* link = head;
    for (int i = 0 ; i < 9 ; ++i)
    {
        Node* newNode = new Node();
        newNode->data = i;
        link->next = newNode;
        link = newNode;
    }
    printListAddress(head);
    // Make array of 10 Node
    Node* arr= new Node[10];
    printArrAddress(arr, 10);
    return 0;
}

And i get

0x1f97c20   0x1f97c40   0x1f97c60   0x1f97c80   0x1f97ca0   
0x1f980d0   0x1f980e0   0x1f980f0   0x1f98100   0x1f98110

In linked list, difference of memory address of each node is 20 and in array is 10 but sizeof(arr[i]) = sizeof(*head) =16. Please explain me the difference. Thanks for all help;

Upvotes: 0

Views: 635

Answers (1)

Sean
Sean

Reputation: 62472

new is free to allocate the memory you request wherever it likes, so you shouldn't assume there's a pattern to the addresses returned.

For an array the items in the array will be next to each other in memory (the array is a contiguous block of bytes). For a type T an item will be sizeof(T) * index bytes into the array.

Upvotes: 2

Related Questions