Horje
How to Modify Struct Members Using a Pointer in C?

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)




Reffered: https://www.geeksforgeeks.org


C Language

Related
How to Write a Command Line Program in C? How to Write a Command Line Program in C?
Simple Personal Diary Management System in C Simple Personal Diary Management System in C
How to Declare a Pointer to a Struct in C? How to Declare a Pointer to a Struct in C?
Length of a String without Using the strlen Function in C Length of a String without Using the strlen Function in C
Build Your Own &#039;cat&#039; Command in C for Linux Build Your Own &#039;cat&#039; Command in C for Linux

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13