Sunday, March 27, 2016

Pointers to Structures

Just like other primitive data types you know, you can also define pointers to the structure too. However, accessing member variables using pointer to structure would be different. In this case, instead of dot(.) operator you have to use arrow(->) operator which is also called reference operator. Here is the example given below:
student student_1 = {0} , *pstudent = NULL;
pstudent = &student_1;
pstudent->roll_number = 20;
strcpy(pstudent->name,” Denis Ritchie”);
pstudent->class = 12;
pstudent->section = ‘A’;
pstudent->marks = 96.9;
strcpy(student_1->school_name,”a4academics.com”);

printf(“Student’s Roll Number : %d\n”, pstudent->roll_number);
printf(“Student’s Name : %s\n”, pstudent->name);
printf(“Student ‘s Class : %d\n”, pstudent->class);
printf(“Student’s Section : %c\n”, pstudent->section);
printf(“Student’s Marks : %f\n”, pstudent->marks);
printf(“Student’s School Name : %s\n”, pstudent->school_name);
Output :
Student’s Roll Number 20
Student’s Name Denis Ritchie
Student ‘s Class 12
Student’s Section A
Student’s Marks 96.9
Student’s School Name a4academics.com
Another way to store structure is by allocating memory dynamically. The only thing you need to remember here is that you have to free that memory when you don’t need them. When you allocate memory using malloc, you have to typecast to the structure that you are going to use in a program. Rest of the stuff is same as above.
pstudent =(student*) malloc(sizeof(student));

/* Your Code*/
free(pstudent);

No comments: