0

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;

3
  • 2
    "in array is 10" - You know that "10" is in hexadecimal, I hope. Commented Sep 26, 2017 at 13:41
  • 1
    There's no reason for your list nodes to be allocated in any meaningful pattern. Your array of nodes, however, is guaranteed to be contiguous and have a stride of sizeof(Node). Commented Sep 26, 2017 at 13:41
  • 1
    But there is also no guarantee what sizeof(Node) is, the compiler can pad it up to a size it sees fit. Commented Sep 26, 2017 at 14:00

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.