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

初始化结构体数组时出现Segmentation Fault(段错误)问题

问题原因

你的代码出现段错误的核心原因是结构体中的modelName是未初始化的字符指针:

  • 声明Car arr[2]时,数组中每个Car实例的modelName都是野指针,指向内存中的随机非法地址。
  • 调用scanf("%s", c[i].modelName)时,程序尝试往这个非法地址写入数据,触发内存访问错误,导致segmentation fault。
解决方案

有两种可靠的修复方式:

方式一:使用固定大小的字符数组替代指针

直接在结构体中把char *modelName改为固定长度的字符数组,这样每个Car实例都会自带一块可写入的内存空间:

#include <stdio.h>
enum carType
{
    sedan,
    suv,
    hatchback,
    muv
};
typedef enum carType carType;

struct Car
{
    int modelNo;
    char modelName[50]; // 改为固定大小的字符数组,可根据需求调整长度
    float price;
    carType type;
};
typedef struct Car Car;

void init(Car* c, int s)
{
    for (int i = 0; i < s; i++)
    {
        scanf("%d", &(c[i].modelNo));
        // 直接用%s写入,注意输入长度不要超过数组大小
        scanf("%s", c[i].modelName);
        scanf("%f", &(c[i].price));
        scanf("%d", &(c[i].type));
    }
}

int main()
{
    Car arr[2];
    printf("Enter values for members of array of Cars :\n");
    init(arr, 2);

    return 0;
}

这种方式简单直接,适合能确定输入字符串长度范围的场景。

方式二:动态分配内存

如果需要灵活的字符串长度,可以在读取输入前先为modelName分配内存,注意要在使用完后释放内存避免泄漏:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum carType
{
    sedan,
    suv,
    hatchback,
    muv
};
typedef enum carType carType;

struct Car
{
    int modelNo;
    char *modelName;
    float price;
    carType type;
};
typedef struct Car Car;

void init(Car* c, int s)
{
    char tempBuf[100]; // 临时缓冲区存储输入
    for (int i = 0; i < s; i++)
    {
        scanf("%d", &(c[i].modelNo));
        scanf("%s", tempBuf);
        // 分配足够内存存储输入的字符串(+1是为了存结束符'\0')
        c[i].modelName = malloc(strlen(tempBuf) + 1);
        if (c[i].modelName == NULL) {
            perror("malloc failed");
            exit(1);
        }
        strcpy(c[i].modelName, tempBuf);
        
        scanf("%f", &(c[i].price));
        scanf("%d", &(c[i].type));
    }
}

int main()
{
    Car arr[2];
    printf("Enter values for members of array of Cars :\n");
    init(arr, 2);

    // 使用完后记得释放内存
    for (int i = 0; i < 2; i++) {
        free(arr[i].modelName);
    }

    return 0;
}

这种方式适合字符串长度不确定的场景,但需要注意手动管理内存,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Pisers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:30:54