C语言结构体数组与文件读取代码错误求助
Fixing Your C File Handling Code & Understanding Struct/Pointer Syntax
Hey there! Since you come from a Pascal background, it makes total sense that C's approach to structs, pointers, and memory management feels confusing at first—let's walk through your code issues, explain the key differences, and get your program working.
First, Let's Break Down the Errors in Your Code
Your code has a few critical issues that are causing those pointer/struct-related errors:
- Undefined
my_stringtype: You declaredmy_string string;but never defined this type, and you aren't even using it—we can just remove this line entirely. - Unallocated pointers in your struct: In Pascal, strings are often managed automatically, but in C,
char *nameandchar *ageare just pointers—they don't point to any valid memory yet. If you try to read data into them withfscanf, you'll get memory corruption (this is probably the biggest source of your errors). - Problematic
fscanfformat strings: Your%[^\n]\nformat is causing issues with leftover newline characters in the input buffer, leading to empty reads. - Potential issues with variable-length arrays (VLAs):
Person person_array[numberOfLines];is a C99 VLA, which isn't supported by all compilers, and can cause stack overflow ifnumberOfLinesis large.
Key Concept: . vs -> vs * in C
Let's clarify these since they're tripping you up:
.(dot operator): Use this when you're working with a direct instance of a struct (likeperson_array[i], which is aPersonvariable). This is similar to Pascal's.for record fields.->(arrow operator): Use this when you have a pointer to a struct (e.g.,Person *p = &person_array[0];). It's shorthand for(*p).name—in Pascal terms, this would be likep^.name.*(dereference operator): This gets the value that a pointer points to. So ifpis a pointer to aPerson,*pgives you the actualPersonstruct instance.
Fixed Code with Explanations
Let's rewrite your code to fix these issues, using fixed-size character arrays (easier for beginners than dynamic memory):
#include <stdio.h> #include <stdlib.h> // For malloc/free if we use dynamic allocation // Use fixed-size char arrays instead of unallocated pointers typedef struct { char name[50]; // Allocate enough space for names (adjust size as needed) char age[10]; // Enough space for age strings (e.g., "25" or "100") } Person; void write_lines_to_terminal(Person person_array[], int numberOfLines) { for (int i = 0; i < numberOfLines; i++) { // Use . since person_array[i] is a direct Person instance printf("name: %s, age: %s\n", person_array[i].name, person_array[i].age); } } void read_lines_to_terminal(FILE *file_ptr) { int i; int numberOfLines; // Read the number of lines, then skip the leftover newline fscanf(file_ptr, "%d", &numberOfLines); fgetc(file_ptr); // Consume the newline after the number // Option 1: Use a VLA (C99+). For better portability, use malloc below. Person person_array[numberOfLines]; // Option 2: Dynamic allocation (safer for large numberOfLines) // Person *person_array = malloc(numberOfLines * sizeof(Person)); // if (person_array == NULL) { // printf("Memory allocation failed!\n"); // return; // } for (i = 0; i < numberOfLines; i++) { // The leading space skips any leading whitespace (like newlines) // %[^\n] reads until the newline character fscanf(file_ptr, " %[^\n]", person_array[i].name); fscanf(file_ptr, " %[^\n]", person_array[i].age); } write_lines_to_terminal(person_array, numberOfLines); // Uncomment if using dynamic allocation // free(person_array); } // Example main function to test int main() { FILE *file = fopen("people.txt", "r"); if (file == NULL) { printf("Could not open file!\n"); return 1; } read_lines_to_terminal(file); fclose(file); return 0; }
Notes on Your Input File
Make sure your input file follows this format (first line is the number of people, then each person's name and age on separate lines):
2 Alice Smith 30 Bob Johnson 25
Key Takeaways for Pascal Developers
- C doesn't manage string memory automatically—you have to allocate space (either fixed arrays or
malloc/free). - Use
.for struct instances,->for struct pointers. - Always handle input buffer cleanup (like leftover newlines) when using
fscanf.
内容的提问来源于stack exchange,提问作者Khang
相关产品推荐
相关产品推荐

