gpt4 book ai didi

c - FOR 循环时出现段错误(核心转储)

转载 作者:行者123 更新时间:2023-11-30 14:22:28 25 4
gpt4 key购买 nike

这是 C: 上的代码

这是函数:

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

struct worker
{
char firstName;
char lastName;
char middleName;
int age;
float height;
};

void enterData();
void displayData();
void makeCalc();

struct worker *b;
int count;

int main(void)
{
enterData();
displayData();
makeCalc();
free(b);
return 0;
}

void enterData()
{
char firstName;
char lastName;
char middleName;
int age;
float height;


printf("Количество работников: \n");
scanf("%d", &count);

if(count <= 0){
exit(0);
}

b = (struct worker *)malloc(count*sizeof(struct worker));


for(int i = 0; i<count; i++){
printf("Введите имя, фамилию, отчестве, возраст и рост через пробел: \n");
scanf("%s%s%s%d%f", &firstName, &lastName, &middleName, &age, &height);
struct worker a = (struct worker) {firstName, lastName, middleName, age, height};
b[i] = a;
}

}

当这部分运行时,如果程序显示 Segmentation fault (core dumped) :

for(int i = 0; i<count; i++){
printf("Enter name, surname and middle name: \n");
scanf("%s%s%s%d%f", &firstName, &lastName, &middleName, &age, &height);
struct worker a = (struct worker) {firstName, lastName, middleName, age, height};
b[i] = a;

这可能是什么原因?我是 C 语言新手;

P.S 我在 ubuntu 12.04 上使用 GCC 编译器。和通用文本编辑器。

最佳答案

你的问题是:

    scanf("%s%s%s%d%f", &firstName, &lastName, &middleName, &age, &height);

您扫描字符串,但您的变量只是字符:

   char firstName;
char lastName;
char middleName;

关于c - FOR 循环时出现段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13704134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com