[英]C pointers as struct members, allocation, initialization
我正在研究代数应用程序,这是代码
struct quotient
{
int numerator;
int denominator;
};
struct term
{
struct quotient coefficient;
char varname;
struct quotient power;
};
struct function
{
struct term* terms;
char* operators;
struct quotient coefficient;
struct quotient power;
};
//Constructor Functions
struct quotient NewQuotient()
{
struct quotient temp;
printf("Enter the numerator\n");
scanf("%d", &temp.numerator);
printf("Enter the denominator\n");
scanf("%d", &temp.denominator);
return temp;
}
char NewVarname()
{
char temp;
printf("Enter the variable letter: \n");
scanf("%c", &temp);
return temp;
}
struct term NewTerm()
{
//broken, won't let you enter a variable name, sets it to x by default until that's resolved
struct term temp;
printf("Enter the coefficient: ");
temp.coefficient = NewQuotient();
printf("Enter the variable name: \n");
temp.varname = NewVarname();
temp.varname = 'x';
printf("Enter the power: ");
temp.power = NewQuotient();
return temp;
}
void NewFunction(struct function* func, int size)
{
//so far so good
unsigned i;
func->terms = (struct term*)calloc(size, sizeof(struct term));
//loop to initialize each term
for(i = 0; i < size; i++)
{
func->terms[i] = NewTerm();
}
return;
}
int main(){
struct function fofx;
NewFunction(&fofx, 2);
DisplayFunction(&fofx, 2);
DeleteFunction(&fofx);
return 0;
}
这是输出:
输入分子:
1
输入分母:
2
输入分子:
3
输入分母:
4
....
等,直到循环结束。
NewTerm中的一半语句似乎根本没有执行,但程序似乎成功分配并初始化了一个新函数。 非常感谢任何帮助,我对此非常困惑。 我没有包含显示和删除功能,它们工作正常,但如果它们有用,我可以在这里添加它们。
你没有给calloc提供合适的大小,它应该是sizeof (struct term)
而不是sizeof (int)
。 这可能是问题,这取决于实际的尺寸struct term
,你有什么价值size
。
关于NewTerm
没有被调用,这可能是因为你没有调用它。
使用scanf
,通常需要获取Return键和数字。
你有:
scanf("%d", &temp.numerator);
你真的想要:
scanf("%d\n", &temp.numerator);
您还应该使用验证来确保只输入数字或者您将获得古怪的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.