程序要求用户输入两个值,在指针中存储值后,打印分段错误并终止。为什么?
// c program to add two numbers using pointers
#include <stdio.h>
int main()
{
int *ptr1, *ptr2, sum;
printf ("Enter the two numbers:\n");
scanf ("%d %d", ptr1, ptr2);
sum = *ptr1 + *ptr2;
printf("The result is %d", sum);
return 0;
答案 0 :(得分:1)
这是因为你没有为ptr1和ptr2分配内存。
#include <stdio.h>
int main()
{
int *ptr1=0, *ptr2=0, sum=0;
ptr1= malloc(sizeof(int));
if(0 == ptr1) //Check if mem allocation is successful.
{
printf("Failed to allocate memory for ptr1\n");
return 0;
}
ptr2= malloc(sizeof(int));
if(0 == ptr2) //Check if mem allocation is successful.
{
printf("Failed to allocate memory for ptr2\n");
free(ptr1); //Free ptr1 memory
return 0;
}
printf ("Enter the two numbers:\n");
scanf ("%d %d", ptr1, ptr2);
sum = *ptr1 + *ptr2;
printf("The result is %d", sum);
free(ptr2); //Free ptr2 memory
free(ptr1); //Free ptr1 memory
return 0;
}