[英]Segmentation Error in C programming
我正在嘗試用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 );
}
我在這里做錯了什么? 如何解決此錯誤?
scanf("%d", num1);
scanf("%d", num2);
scanf需要一個地址,當您將它們作為函數中的指針傳遞時,num1和num2已經包含該地址。
另一件事需要更改:
printf("%d + %d = %d \n",*num1,*num2,total );
*num1
取消引用指針以提供值
我在這里做錯了什么? 如何解決此錯誤?
問題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);
當num1
和num2
的類型為int*
。 您需要成為:
scanf("%d", num1);
scanf("%d", num2);
問題3
您正在使用
printf("%d + %d = %d \n",&num1,&num2,total );
給定num1
和num2
的類型,則需要為:
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);
}
盡管@ jayant-指出了錯誤
#define calculation1 main
void calculation1(int *num1, int *num2) {
因此, calculation1
將被main
取代,簡而言之,這就是您的main
函數。
這是無效的,無論如何都應避免。 我很困惑您如何撥打電話或接受命令行參數? 但這絕對是不正確的。
只需執行此操作-
int main(void)
或int main(int argc,char *argv[])
並將num1
和num2
聲明為int
變量,然后在其中輸入並執行所需的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.