How to access pointer inside a structure in c

pointer inside a structure

It is not a big deal to access pointer inside a structure in c but still, there are a lot of people who make mistakes. In this article, I will write a method to describe the way to how to access pointer from a structure.

Here I am assuming you have already knowledge of structure and pointers. If you want a quick revision, please read the below articles.

  1. structure in  C
  2. pointers in C

Let’s take an example to understand the way to how to access pointer from a structure in C.

Suppose StudentInfo is a structure, this structure contains all the information of student like their name, age, roll number, address. Our requirement here to create a method to write the information into the structure. Before reading this example if you don’t know the dynamic memory allocation, please read the below articles.

  1. Dynamic memory allocation
  2. Problem with Dynamic Memory Allocation
  3. How to dynamically allocate a 1D and 2D array in c

See below example code,

 

For the efficiency, a pointer to the structures is generally passed to functions. The members of structures that are passed within the functions are accessed to perform dereferencing a structure pointer and a selecting a member using the dot operator ( . ). It is very difficult to dereference the structure pointer every time.

Therefore, C provides a special pointer operator, (called arrow) to access a member of a structure pointed to by a pointer variable. The operator is a combination of minus symbol, -, followed by a greater-than symbol, >.

Arrow operator is exactly equivalent to a dereference operation followed by the dot ( . ) operator as shown below:

(*pTomInfo).age;

Remember, this is the same as:

pTomInfo->age;

If you want to learn more about the c language, here 10 Free days  C video course for you.

C tutorial

 

Some Important Observations of the above code:

1. The below two statements are very necessary, generally, people make mistakes here and forget to allocate separate memory for the pointers within the structure.

Like in above example, I have allocated separate memory for the student name and address.

 

 

2. Generally, people deallocates the memory allocated for structure pointers before deallocating the memory of structure members.

3. Use the fgets in place of the scanf and gets. It prevents from the overflow.

 



Leave a Reply