使用带有3个输入变量的scanf时出现分段错误

1 c malloc scanf segmentation-fault

不知道为什么我在这里遇到分段错误:

//I define the variables used for input

int *numberOfDonuts;
    numberOfDonuts = (int *)malloc(sizeof(int));

char *charInput;
    charInput = (char *)malloc(sizeof(char));   

int *numberOfMilkshakes;
    numberOfMilkshakes = (int *)malloc(sizeof(int));

//Then attempt to read input
scanf("%c %d %d", &*charInput, &*numberOfDonuts, &*numberOfMilkshakes);
Run Code Online (Sandbox Code Playgroud)

然后我在这一行得到了一个分段错误.无法解决我做错了什么?

And*_*per 6

您使用分配变量的方式过度复杂化了.这应该做你想要的:

int numberOfDonuts;
char charInput;
int numberOfMilkshakes;

scanf("%c %d %d", &charInput, &numberOfDonuts, &numberOfMilkshakes);
Run Code Online (Sandbox Code Playgroud)

对于类似的基本类型int,char您不必为它们显式分配内存.编译器会为您处理.

即使按照你的方式分配它们,你最终得到的是指向值而不是值本身的指针.鉴于需要scanf一堆指针,不需要取消引用指针,然后再次获取它的地址,这就是你要做的事情.以下内容也适用:

int *numberOfDonuts;
    numberOfDonuts = malloc(sizeof(int));

char *charInput;
    charInput = malloc(sizeof(char));   

int *numberOfMilkshakes;
    numberOfMilkshakes = malloc(sizeof(int));

scanf("%c %d %d", charInput, numberOfDonuts, numberOfMilkshakes);
Run Code Online (Sandbox Code Playgroud)