[英]segmentation fault with scanf and pointers
我是C語言的新手,所以解決方案可能微不足道,但我似乎無法弄清楚。 在程序中運行getDemensions()時出現分段錯誤:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void getDemensions(double *, double *);
void calculateAreaAndCircumference(double, double, double *, double *);
void displayRectangleInformation(double, double, double, double);
int main() {
double length, width, area, circumference;
getDemensions(&length, &width);
calculateAreaAndCircumference(length, width, &area, &circumference);
displayRectangleInformation(length, width, area, circumference);
}
void getDemensions(double *length, double *width) {
printf("Enter rectangle length: ");
scanf("%lf", *length);
printf("Enter rectangle width: ");
scanf("%lf", *width);
}
還值得注意的是:我嘗試在scanf()中的變量前面使用“&”,而沒有分段錯誤,但是輸入未保存。
scanf
需要一個指針。 由於length
和width
已經是指針,您只需將它們傳遞給scanf
:
void getDemensions(double *length, double *width) {
printf("Enter rectangle length: ");
scanf("%lf", length);
printf("Enter rectangle width: ");
scanf("%lf", width);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.