如何编写结构体变量的读取与显示函数?批量结构体元素读写代码优化求助
Fixing Your Struct Input/Output Code for Multiple Elements
Hey there! Let's walk through the issues in your code and fix them up. The core problems are how you're passing structs to functions (you're modifying copies instead of the original data) and not having a way to store multiple struct instances. Here's the breakdown:
What's Wrong with the Original Code?
- Pass-by-value instead of pass-by-reference: When you pass a struct to
readDataorread, you're sending a copy of the struct. Any changes you make inside those functions only affect the copy, not the original struct inmain. That's why your display function shows garbage or unchanged values. - No storage for multiple elements: You're using a single
struct datavariable to try to store 3 entries—this just overwrites the same data each time, so you can't keep all 3 values.
Corrected Code
#include <stdio.h> // Define the struct type struct data{ int d, m, y; }; // Read a single struct instance using a pointer (modifies original data) void readData(struct data *element){ printf("\nEnter date (dd-mm-yyyy): "); // Use %d-%d-%d to match the expected input format scanf("%d-%d-%d", &element->d, &element->m, &element->y); } // Read n structs from an array void read(struct data elements[], int n){ for(int i = 0; i < n; i++){ printf("Entry %d:", i + 1); readData(&elements[i]); } } // Display a single struct instance void display(struct data element){ printf("\n%d.%d.%d", element.d, element.m, element.y); } // Display all n structs from the array void displayN(struct data elements[], int n){ printf("\n--- All Entered Dates ---"); for(int i = 0; i < n; i++){ display(elements[i]); } printf("\n"); } int main() { const int numEntries = 3; // Create an array to hold 3 struct instances struct data dd1[numEntries]; read(dd1, numEntries); displayN(dd1, numEntries); return 0; }
Key Changes Explained
- Pointer for
readData: By usingstruct data *element, we pass the memory address of the struct. This lets us modify the original struct in the array instead of a temporary copy. We useelement->d(instead ofelement.d) to access members through a pointer. - Array for multiple elements:
struct data dd1[numEntries]creates an array of 3 structs, so each entry gets stored in its own slot instead of overwriting the same data. - Fixed input format: The
scanfformat string%d-%d-%dmatches thedd-mm-yyyyprompt, so users can input dates like05-10-2024and have the values read correctly. - Clearer output: Added labels for entries and a header for the displayed dates to make the output easier to read.
Test this code—you'll be able to enter 3 distinct dates and see all of them printed out correctly!
内容的提问来源于stack exchange,提问作者kammy
相关产品推荐
相关产品推荐

