You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_string type: You declared my_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 *name and char *age are just pointers—they don't point to any valid memory yet. If you try to read data into them with fscanf, you'll get memory corruption (this is probably the biggest source of your errors).
  • Problematic fscanf format strings: Your %[^\n]\n format 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 if numberOfLines is 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 (like person_array[i], which is a Person variable). 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 like p^.name.
  • * (dereference operator): This gets the value that a pointer points to. So if p is a pointer to a Person, *p gives you the actual Person struct 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:59:36