[英]Inputting values to structure members using pointers
我正在編寫一個程序,用於使用結構和指針查找兩個有理數的加法,乘法和除法。 我在使用指針輸入數字時遇到問題。 我的代碼應該如何糾正? 謝謝!
#include <stdio.h>
struct rational
{
int nu;
int de;
}*p1,*p2,*p3;
void add()
{
p1->nu = p1->nu*p2->de + p1->de*p2->nu;
p3->de = p1->de * p2->de;
printf("%d\n--\n%d\n",p3->nu,p3->de);
}
void multiply()
{
p3->nu = p1->nu * p2->nu;
p3->de = p1->de * p2->de;
printf("%d\n--\n%d\n",p3->nu,p3->de);
}
void divide()
{
p3->nu = p1->nu * p2->de;
p3->de = p1->de * p2->nu;
printf("%d\n--\n%d\n",p3->nu,p3->de);
}
int main()
{
int a,b,c,d,choice;
printf("Enter the first rational number.\n");
scanf("%d%d",&a,&b);
p1->nu = a;
p1->de = b;
printf("Enter the second rational number.\n");
scanf("%d%d",&c,&d);
p2->nu = c;
p2->de = d;
scanf("%d",&choice);
switch (choice)
{
case 1: add();
break;
case 2: multiply();
break;
case 3: divide();
break;
}
return 0;
}
您永遠不會初始化指針,因此您提供的代碼會調用未定義的行為 。 在實際使用p1之前,p2和p3使它們指向某個現有對象,或者為它們動態分配內存。
例如
#include <stdio.h>
#include <stdlib.h>
struct rational{
int nu;
int de;
} ;
int main(void){
int n, d;
struct rational *p;
p=(struct rational*)malloc(sizeof(struct rational));
printf("Enter the rational number.\n");
/* Indirection
scanf("%d/%d", &n, &d);
p->nu = n;
p->de = d;
*/
scanf("%d/%d", &p->nu, &p->de);//Direct
printf("%d/%d\n", p->nu, p->de);
return 0;
}
解決了。 我在main()
聲明了3個struct rational
變量: p1
, p2
和p3
。 然后我將這些變量的地址導出到具有三個指針作為其原型的函數中。
#include <stdio.h>
struct rational
{
int nu;
int de;
};
void add(struct rational *p1,struct rational *p2,struct rational *p3)
{
p3->nu = (p1->nu)*(p2->de) + (p1->de)*(p2->nu);
p3->de = p1->de * p2->de;
printf("%d\n-\n%d\n",p3->nu,p3->de);
}
void multiply(struct rational *p1,struct rational *p2,struct rational *p3)
{
p3->nu = p1->nu * p2->nu;
p3->de = p1->de * p2->de;
printf("%d\n-\n%d\n",p3->nu,p3->de);
}
void divide(struct rational *p1,struct rational *p2,struct rational *p3)
{
p3->nu = p1->nu * p2->de;
p3->de = p1->de * p2->nu;
printf("%d\n-\n%d\n",p3->nu,p3->de);
}
int main()
{
struct rational p1,p2,p3;
int a,b,c,d,choice;
printf("Enter the first rational number.\n");
scanf("%d/%d", &p1.nu, &p1.de);
printf("Enter the second rational number.\n");
scanf("%d/%d", &p2.nu, &p2.de);
printf("1. Addition 2. Multiplication 3. Division: ");
scanf("%d",&choice);
switch (choice)
{
case 1: add(&p1,&p2,&p3);
break;
case 2: multiply(&p1,&p2,&p3);
break;
case 3: divide(&p1,&p2,&p3);
break;
}
return 0;
}
//Output
//Enter the first rational number.
//3/4
//Enter the second rational number.
//7/9
//1. Addition 2. Multiplication 3. Division: 1
//55
//-
//36
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.