I am having trouble understanding pointer to structure. actually i don't understand that Structure pointer points to the object of the structure or the structure variable.
Can someone clarify what struct pointers point to
I am having trouble understanding pointer to structure. actually i don't understand that Structure pointer points to the object of the structure or the structure variable.
Can someone clarify what struct pointers point to
A pointer to a structure is a variable that holds a memory address that can be assumed to be the starting address of an area of memory is holding data for that type of structure.
A value of NULL is a special value, that can be used to indicate that the pointer is not valid.
Incrementing or decrementing the pointer will change the address held in the pointer variable by the size of the structure, making it easier to work with multiple instances of that structure held in contiguous memory addresses (such as happens with an array).
Addition and subtraction work that way too.
A simple example might make it easier.
Code:#include <stdio.h> typedef struct { int X, Y; } Point; int main() { Point point = {1,1}; Point *p = &point; printf("(%d,%d)", p->X, p->Y); return 0; }
It seems that a pointer to a structure is always a point to the object of the structure. The object of the structure must always be initialized before it can be used.
Not necessarily. It must have been declared to even have an object in memory from which you can get the address. Another way to get a pointer is to allocate a memory object for the structure at runtime (e.g. using malloc()).The object of the structure must always be initialized before it can be used.
Just a small comment on -> operator. The . operator have precedence over * (indirection) operator, so, something like this:
The correct usage would be (*p).x = 1;Code:struct pt { int x, int y }; struct pt point; struct pt *p = &point; ... *p.x = 1; // don't work. Trying to use p.x (not p) as a pointer!
Then ANSI C (equivalent to ISO C89) added the -> operator, which applies to structures and unions pointers.
You can interpret p-> as a shortcut to "(*p).".Code:p->x = 1;
Last edited by flp1969; 12-24-2022 at 08:38 AM.