[英]How do i assign a value using scanf to a member of a Struct type variable whose array is created dynamically
Code Visualisation Image代码可视化图像
My main problem is how do I take inputs using scanf to the coeff and exp members declared in the array of Terms which is referenced by a Poly variable member named as ptr and this Poly variable is further referenced by a pointer p.我的主要问题是如何使用 scanf 对在术语数组中声明的 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));
}
}
There are many issues.有很多问题。
This is the corrected code with explanations in the end of line comments.这是更正的代码,行末注释中有解释。 The comments without
**
show improvements which were not actual errors没有
**
的评论显示了不是实际错误的改进
#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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.