Question regarding memory addresses of pointers to structs

Hi
I have this struct declaration to create a linked list

1
2
3
4
5
struct node
{
	string y;
	node* next;
};


If I create a linked list of 3 nodes

A->B->C->NULL

A->y is "a"
B->y is "b"
C->y is "c"

Since they are consecutive in memory. How far apart are the strings in memory?

I tried doing something like

int n = &(head->next->x)-&(head->x);

The problem is that I got 6 while debugging and 2 otherwise.

Why is that?

Thanks
Since they are consecutive in memory
They are actually not.
If you are doing
1
2
3
A = new node;
B = new node;
//etc. 
They can be everywhere in memory.

Even if you will make sure that they are consequent (by allocating an array of them), your function calculating distance is wrong. It calculates distance in strings. That means you do not have any information about distance unless you know string size.

Example:
1
2
3
4
5
6
7
int main()
{
    char* x = (char*)malloc(1000);
    std::string* a = new (x) std::string();
    std::string* b = new (x + 40) std::string();
    std::cout << b - a;
}
5

Last edited on
Topic archived. No new replies allowed.