Referencing Whole Structures
In C, we can assign one structure to another of the same type, which copies the entire content. This is known as referencing a whole structure. Here, we will cover how to reference whole structures and use assignment operations between structure variables.
Explanation
To assign all members of one structure variable to another, both variables must be of the same structure type. Using the assignment operator (=), we can copy all members at once. This technique is often helpful when dealing with large structures, as it avoids copying each member individually.
Example:
#include <stdio.h>
// Defining a Structure for Book
struct Book {
char title[100];
char author[50];
float price;
};
int main() {
// Initializing a structure variable
struct Book book1 = {"C Programming", "Dennis Ritchie", 299.50};
// Declaring another structure variable
struct Book book2;
// Copying book1 data to book2
book2 = book1;
// Displaying data of book2
printf("Title: %s\n", book2.title);
printf("Author: %s\n", book2.author);
printf("Price: %.2f\n", book2.price);
return 0;
}
Output
Author: Dennis Ritchie
Price: 299.50
Copying one structure variable to another only works for non-pointer types. This is because pointers within structures will not copy the memory they point to but only the pointer address. Care should be taken while copying structures that contain pointer members.