gpt4 book ai didi

c - C 编程中的段错误

转载 作者:行者123 更新时间:2023-11-30 18:20:01 27 4
gpt4 key购买 nike

我正在尝试用 C 语言编译程序,但我不断收到以下错误:

Segmentation fault

这是代码:

#include <stdio.h>
#define calculation1 main
void calculation1(int *num1, int *num2) {

int total;

printf("Program One: \n");
printf("=========== \n");

printf("Number One: ");
scanf("%d", &num1);

printf("Number Two: ");
scanf("%d", &num2);

total = *num1 + *num2;

printf("%d + %d = %d \n",&num1,&num2,total );
}

我在这里做错了什么?我该如何修复这个错误?

最佳答案

What am I doing wrong here? How can I fix this error?

问题1

通过使用

#define calculation1 main
void calculation1(int *num1, int *num2) {

您实际上正在使用:

void main(int *num1, int *num2) {

这是错误的。 main 需要是:

int main(void) {

int main(int argc, char** argv) {

您的程序可能会出现未定义的行为。

问题1

您正在使用

scanf("%d", &num1);
scanf("%d", &num2);

num1num2 的类型为 int* 时。你需要:

scanf("%d", num1);
scanf("%d", num2);

问题3

您正在使用

    printf("%d + %d = %d \n",&num1,&num2,total );

鉴于 num1num2 的类型,需要是:

    printf("%d + %d = %d \n", *num1, *num2, total );

修复

您的程序需要进行一些修改。尝试:

#include <stdio.h>
#define calculation1 main
int calculation1() {

int num1; // Not int*. If you use int*, you'll need to allocate memory
int num2;

int total;

printf("Program One: \n");
printf("=========== \n");

printf("Number One: ");
scanf("%d", &num1); // You need to use &num1 since num1 is of type int.

printf("Number Two: ");
scanf("%d", &num2);

total = num1 + num2;

printf("%d + %d = %d \n", num1, num2, total);
}

关于c - C 编程中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33304537/

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