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

如何打印接收用户输入的typedef struct变量?解决段错误问题

问题分析与修复

你的代码触发段错误的核心原因是结构体中的char *name未分配有效内存:当你定义candidate c;时,c.name是一个野指针(指向随机的内存地址),scanf("%s", c.name)尝试往这个非法地址写入数据,直接导致内存访问错误。同时代码里的换行符 是错误写法,应该用\n才能正确换行。

修复方案1:使用固定大小字符数组

把结构体里的指针替换为固定长度的字符数组,提前预留内存空间,简单直接:

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

// 用固定大小数组存储名字,这里设为50字节(含结束符)
typedef struct
{
    char name[50];
    int vote;
} 
candidate;

candidate get_candidate(char *prompt);

int main(void)
{
    candidate president = get_candidate("Enter candidate: ");
    printf("%s\n", president.name);
    printf("%i\n", president.vote);                                

}

candidate get_candidate(char *prompt)
{
    printf("%s\n", prompt);

    candidate c;
    printf("Enter a name: ");
    // 限制输入长度为49,避免数组越界(留1位给字符串结束符\0)
    scanf("%49s", c.name);

    printf("Enter votes: ");
    scanf("%i", &c.vote);

    return c;
}

修复方案2:动态分配内存

如果需要灵活的字符串长度,可通过malloc动态分配内存,注意使用后要手动释放避免内存泄漏:

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

typedef struct
{
    char *name;
    int vote;
} 
candidate;

candidate get_candidate(char *prompt);

int main(void)
{
    candidate president = get_candidate("Enter candidate: ");
    printf("%s\n", president.name);
    printf("%i\n", president.vote);

    // 释放动态分配的内存
    free(president.name);                                
}

candidate get_candidate(char *prompt)
{
    printf("%s\n", prompt);

    candidate c;
    // 初始分配100字节内存,可根据需求调整
    c.name = malloc(100 * sizeof(char));
    if (c.name == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        exit(1);
    }

    printf("Enter a name: ");
    // 限制读取长度不超过分配的内存(99位,留1位给结束符)
    scanf("%99s", c.name);

    printf("Enter votes: ");
    scanf("%i", &c.vote);

    return c;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:27:23