Program to illustrate a function that assigns value to the structure
C Program: Assigning Value to a Structure
Introduction
In this C program, we will demonstrate how to assign values to a structure using a function. Structures in C allow you to group together variables under a single name, making it easier to organize and manipulate data.
Program Explanation
Step 1: Define the Structure
struct Point {
int x;
int y;
};
We define a structure named Point that contains two integer members: x and y.
Step 2: Create a Function to Assign Values
void assignValues(struct Point *p, int xVal, int yVal) {
p->x = xVal;
p->y = yVal;
}
We create a function named assignValues that takes three arguments: a pointer to a Point structure, and two integers xVal and yVal. Inside the function, we assign the values of xVal and yVal to the respective members of the structure pointed to by p.
Step 3: Using the Function
int main() {
struct Point myPoint;
assignValues(&myPoint, 10, 20);
printf("x = %d, y = %d\n", myPoint.x, myPoint.y);
return 0;
}
In the main function, we create a variable myPoint of type struct Point. We then call the assignValues function, passing a pointer to myPoint along with the values 10 and 20. This function call will set x to 10 and y to 20 in the structure.
Finally, we print the values of x and y using printf.
Output
x = 10, y = 20
Conclusion
This program demonstrates how to use a function to assign values to a structure in C. By passing a pointer to the structure, we can modify its members within the function, allowing for more organized and flexible data manipulation.