Pointers as Member of Structure in C

pointers as member

A pointer could be a member of structure, but you should be careful before creating the pointer as member of structure in C. Generally we take a pointer as a member when we don’t know the length of the data which need to store.

Let’s see an example to the better understanding,

The above structure “Info” contains two members, integer variable (iLen) and a pointer to the character (pcName).

How to access pointer member of structure in C

Similar to another members pointer member is also access by the structure variable or pointer with the help of dot ( . ) or arrow ( -> ) operator. The left (first) operand of the operator should be variable of structure or pointer to the structure and right (second) operand shall name of a pointer member that you want to access.

See the below code, in which we are creating a structure variable and initializing the variable with literal string and their length. We are also assigning the address of the structure variable (MyInfo) to the pointer to the structure (ptrMyInfo).

 

pointer as member in structure

 

If you like the video course, you can check this course created by my friends Kenny Kerr. The course contains video lectures of 4.13-hour length covering all basic topics of c language.

How to assign a value to a pointer member of structure in C

Before assigning a value to a pointer you should assign a valid memory. If you don’t assign the valid memory, you will get the undefined behavior. There is two way to access the value of a pointer member of a structure in C.

1.  Using the structure variable

 

pointer as member

 

How above program works?

In the above program, MyInfo is a structure variable. Using the MyInfo we can access the members of the structure piData and pcName. As we know that we have to provide a valid memory to the pointer before assigning a value, so here I am using the malloc (memory management function) to allocate heap memory for the pointers.

After the allocation of the memory, I am copying the data in piData and pcName and displaying the copied data on the console using the printf.

2.  Using the pointer to the structure

Similar to the structure variable you can access the pointer member using the pointer to structure. But the difference is that when you are going to access using the pointer to structure you should assign memory to the pointer. See the below example code,

 



Leave a Reply