c-如何使用scanf将值赋给数组是动态创建的Struct类型变量的成员



代码可视化图像

我的主要问题是如何使用scanf对Terms数组中声明的coeff和exp成员进行输入,该数组由名为ptr的Poly变量成员引用,该Poly变量由指针p进一步引用。

#include <stdio.h>
struct Term
{
int coeff;
int exp;
};
struct Poly
{
int terms;
struct Terms *ptr;
};
int main(void)
{
return 0;
}
//creating the array dynamically
struct Term *createPoly()
{
struct Poly *p;
p = (struct Poly *)malloc(sizeof(struct Poly));
printf("Input the number of terms in the polnomial:n");
scanf("%d", p->terms);
p->ptr = (struct Term *)malloc(sizeof(struct Term) * p->terms);
return p;
}
//inputting the values
void input(struct Poly *p)
{
for (int i = 0; i < p->terms; i++)
{
printf("Input the term %d coefficient and exponent value!", i);
scanf("%d%d", &(p->(ptr + i).coeff));
}
} 

存在许多问题。

这是经过更正的代码,行末注释中有解释。没有**的评论显示了不是实际错误的改进

#include <stdio.h>
#include <stdlib.h>                   // ** you forgot this
struct Term
{
int coeff;
int exp;
};
struct Poly
{
int nbofterms;                      // nbofterms is better than terms
struct Term* ptr;                   // ** use Term instead of Terms
};
int main(void)
{
return 0;
}
//creating the array dynamically
struct Poly* createPoly()             // ** you want a struct Poly and not a struct Term
{
struct Poly* p;
p = malloc(sizeof(struct Poly));    // (struct Poly*) cast not needed
printf("Input the number of terms in the polnomial:n");
scanf("%d", &p->nbofterms);             // & added
p->ptr = malloc(sizeof(struct Term) * p->nbofterms);  // cast not needed
return p;
}
//inputting the values
void input(struct Poly* p)
{
for (int i = 0; i < p->nbofterms; i++)
{
printf("Input the term %d coefficient and exponent value!", i);
scanf("%d", &p->ptr[i].coeff);    // ** only one %d and expression corrected
}
}

最新更新