So let's say i have a struct pointer called A and struct pointer called B:
struct example{
//variables and pointers
}*A
and then i have a pointer of datatype struct example:
struct example *B=malloc(sizeof(struct example));
If i do
A=B;
does this arithmetic operation mean that whatever struct pointer B is pointing to will be what struct pointer A is also pointing to? I get it with primitive datatype and pointers but struct confuse me because they have variables inside..
assume struct pointer A is set and everything
Yes... A and B are pointers, not values. When you say A = B, you are saying "set the pointer A to point to the same thing that B is pointing to" -- or, more specifically, both A and B will contain the same memory address after the assignment.
What you are really doing when you use A->someVar
{address of someVar} = {memory address of structure} + {offset of someVar in bytes relative to the start of the structure}
Yes with the following lines of code, A should point to the same location, B was pointing to.
You should think of pointers as just another
unsigned long
variable which holds an address to a memory, (since the pointer just points to the address it holds).Just as with any other variables, you can copy the address stored in one pointer variable to another.
All you're doing is making A and B point to the same struct. For example, suppose your malloc() call reserved space for your struct at address 0x1000 (just an example).
Now, after your malloc(), B just holds the number 0x1000. So when you do A = B, you're just setting A to 0x1000 also. That way B->var1 is the exact same entity as A->var1.
Yes, the following code:
will lead to
A
pointing to the same memory asB
does. However note, that changing the value of the pointer itself (B
) will have no effect on the other pointer (A
), so for example when you do:the pointer
A
will still point to the memory, where the instance ofstruct example
used to reside and thusA
will become an invalid (dangling) pointer.a pointer saves an address of data in memory, the call of
malloc
return the the address of the first word where the memory areay you have allocated for your data starts.You could imagine a pointer just like a piece of paper where you write down the number of a building, when you enter it you'll find apartments witch also have numbers and so on can it go.
So assigning the value of a pointer to an other pointer is just like taking another piece of paper an writing the number from the first paper on it.
Primitive data types and/or other pointers inside the
struct
are just like the apartments, they may show you some concrete stuff or let you enter some other area where you can find other stuff.