Open In App

How to Modify Struct Members Using a Pointer in C?

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, we use structure to group multiple different types of variables inside a single type. These different variables are called the members of structures. In this article, we will discuss how to modify the struct member using a pointer in C.

Example

Input:
myStruct.mem1 = 10;
myStruct.mem2 = 'a';

Output:
myStruct.mem1 = 28;
myStruct.mem2 = 'z';

Modify Struct Members Using Pointer

We can declare a pointer variable that points to the instance of a structure. To modify the value of this structure member using the pointer, we can dereference the structure pointer and use either the dot operator (.) or the arrow operator(->) as shown:

myStructPtr->mem1 = 28;
or
(*myStructPtr).mem1 = 28;

C++ Program to Modify Struct Members Using a Pointer

C




// C program to modify structure members using pointer
#include <stdio.h>
  
typedef struct myStructure {
    int mem1;
    char mem2
} MyStructure;
  
int main()
{
    MyStructure myStruct = { 10, 'a' };
    MyStructure* myStructPtr = &myStruct;
  
    printf("Original Structure: (%d, %c)\n", myStruct.mem1,
           myStruct.mem2);
  
    myStructPtr->mem1 = 28;
    (*myStructPtr).mem2 = 'z';
  
    printf("Modified Structure: (%d, %c)\n", myStruct.mem1,
           myStruct.mem2);
  
    return 0;
}


Output

Original Structure: (10, a)
Modified Structure: (28, z)

Time Complexity: O(1)
Space Complexity: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads