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 a 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.
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 students 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.
- Dynamic memory allocation
- Problem with Dynamic Memory Allocation
- How to dynamically allocate a 1D and 2D array in c
See below example code,
#include <stdio.h> #include<stdlib.h> #include <string.h> //Calculate size of structure #define SIZE_STRUCTURE(x) sizeof(x) //Size of the student name #define NAME_SIZE 40 //Size of the address #define ADDRESS_SIZE 80 //structure template typedef struct { int age; int roll_number; char *name; char *address; } sStudentInfo; //To clear input buffer void ClearNewLines(void) { int c; do { c = getchar(); } while (c != '\n' && c != EOF); } //Function to write information into the structure sStudentInfo* writeStudentInfo(void) { sStudentInfo *writeInfo = NULL; //declare pointer to structure int studentAge = 0; //declare var to store student age int studentRollNumber = 0; //declare var to store student roll number char studentName[NAME_SIZE] = { 0 }; //declare array to store student name char studentAddress[ADDRESS_SIZE] = { 0 }; //declare array to store student Address writeInfo = malloc(SIZE_STRUCTURE(sStudentInfo));//Allocate memory for structure pointer if (writeInfo == NULL) return NULL; printf("Enter the Age: "); //Enter Age of the student scanf("%d", &studentAge); ClearNewLines(); //Clear new Line writeInfo->age = studentAge; // Write age printf("\nEnter the roll number: ");//Enter roll number of the student scanf("%d", &studentRollNumber); ClearNewLines(); //Clear new Line writeInfo->roll_number = studentRollNumber; printf("\nEnter the name: ");//Enter name of the student fgets(studentName, NAME_SIZE, stdin); writeInfo->name = malloc(NAME_SIZE); if (writeInfo->name == NULL) return NULL; strncpy(writeInfo->name, studentName, NAME_SIZE); printf("\nEnter the address: "); //Enter addressof the student fgets(studentAddress, ADDRESS_SIZE, stdin); writeInfo->address = malloc(ADDRESS_SIZE); if (writeInfo->address == NULL) return NULL; strncpy(writeInfo->address, studentAddress, ADDRESS_SIZE); return writeInfo; } //Main function int main(int argc, char *argv[]) { sStudentInfo *pTomInfo = NULL; pTomInfo = writeStudentInfo(); if (pTomInfo == NULL) { printf("Fail to write student info\n"); return 0; } printf("\n\n\n\n\n\n<!**** Read Information of student ****!>\n\n\n\n\n\n"); printf("Age: %d\n", pTomInfo->age); //Print Age of the student printf("Roll number: %d\n", pTomInfo->roll_number);//Print roll number of the student printf("Name: %s\n", pTomInfo->name);//Print name of the student printf("Address: %s\n", pTomInfo->address);//Print address of the student free(pTomInfo->name); //free allocated memory for name pTomInfo->name = NULL; //Avoid to make dangling pointer free(pTomInfo->address); //free allocated memory for address pTomInfo->address = NULL; //Avoid to make dangling pointer free(pTomInfo); //free allocated memory for structure pTomInfo = NULL; //Avoid to make dangling pointer return 0; }
Output:
For 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 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.
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.
writeInfo->name = malloc(sizeof(studentName)); if(writeInfo->name == NULL) return NULL;
writeInfo->address = malloc(sizeof(studentAddress)); if(writeInfo->address == NULL) return NULL;
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 the overflow.
Recommended Posts for you
- Create a students management system in C.
- Create an employee management system in C.
- Top 11 Structure Padding Interview Questions in C
- structure in C: you should know in depth
- What is flexible array member in c?
- What is importance of struct hack in c?
- How to use the structure of function pointer in c language?
- Function pointer in structure.
- Pointer Arithmetic in C.
- Memory Layout in C.
- Union in C, A detailed Guide.
- typedef vs #define in C.
- Macro in C, with example code.
- enum in C, you should know.
- You should know the volatile Qualifier.
- 100 C interview Questions.
- Interview questions on bitwise operators in C.
- A brief description of the pointer in C.
- Dangling, Void, Null and Wild Pointers
- 10 questions about dynamic memory allocation.
- File handling in C.
- Pointer in C.
- C language character set.
- Elements of C Language.
- Data type in C language.
- Operators with Precedence and Associativity in C.
- C format specifiers.
- C++ Interview Questions.