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

malloc分配结构体指针后,如何用scanf向结构体写入数据?

结构体指针的scanf写入语法

你已经定义了如下结构体及类型别名:

struct airplanesType
{
    char TractionType[15];
    int superficeAlare;
    int peso;
    int coefficenteDiCarico;
    int rendimento;
    int cordaMedia;
    int distanzaCPCG;
    int distanzaCGCoda;
    int distanzaDragTraction;
    int MaxTraction;
    int ClMax;
    int CDclmax;
};

typedef struct airplanesType aereo;

并通过malloc分配了内存:

aereo *cesna= malloc(sizeof(aereo));

由于cesna是指向结构体的指针,你不需要手动计算内存偏移,直接用指针成员访问操作符->,或者先解引用指针再用**成员访问操作符.**来访问结构体成员,配合scanf写入数据即可。

具体示例

1. 使用->操作符(最常用)

针对字符串类型的TractionType和整数类型的成员,写法如下:

// 写入字符串(%s会读取到空格前,若要读取含空格的内容需用其他格式符)
scanf("%s", cesna->TractionType);
// 写入整数类型成员
scanf("%d", &cesna->superficeAlare);
scanf("%d", &cesna->peso);
scanf("%d", &cesna->coefficenteDiCarico);
// 其余整数成员写法以此类推
scanf("%d", &cesna->rendimento);
scanf("%d", &cesna->cordaMedia);
scanf("%d", &cesna->distanzaCPCG);
scanf("%d", &cesna->distanzaCGCoda);
scanf("%d", &cesna->distanzaDragTraction);
scanf("%d", &cesna->MaxTraction);
scanf("%d", &cesna->ClMax);
scanf("%d", &cesna->CDclmax);

注意:TractionType是数组名,本身会退化为指针,所以不需要加&;而整数成员需要取地址,因为scanf要求传入指向变量的指针。

2. 使用解引用+.操作符

先通过*cesna获取指针指向的结构体实例,再用.访问成员:

scanf("%s", (*cesna).TractionType);
scanf("%d", &(*cesna).superficeAlare);
// 其余成员写法同理

这种写法和->完全等价,但->更简洁直观,实际开发中更常用。

额外提示

  • 记得在使用malloc后检查指针是否为NULL,避免空指针访问:
if (cesna == NULL) {
    perror("malloc failed");
    return 1;
}
  • 如果需要读取包含空格的字符串到TractionType,可以用%[^\n]格式符,但要先处理输入缓冲区的换行符:
getchar(); // 清除之前输入留下的换行符
scanf("%[^\n]", cesna->TractionType);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 11:06:22