gpt4 book ai didi

C 指针作为结构成员、分配、初始化

转载 作者:行者123 更新时间:2023-11-30 14:24:36 26 4
gpt4 key购买 nike

我正在开发代数应用程序,这是代码

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;
}

这是输出:

Enter the numerator:
1
Enter the denominator:
2
Enter the numerator:
3
Enter the denominator:
4
....

等等,直到循环结束。

NewTerm 中的一半语句似乎根本没有执行,但程序似乎成功分配并初始化了一个新函数。非常感谢任何帮助,我对此感到非常困惑。我没有包含显示和删除功能,它们工作正常,但如果它们有帮助,我可以在此处添加它们。

最佳答案

您没有为 calloc 提供正确的大小,应该是 sizeof (struct term) 而不是 sizeof (int)。这可能是问题所在,具体取决于 struct term 的实际大小以及 size 的值。

关于 NewTerm 没有被调用,这可能是因为您没有调用它。

关于C 指针作为结构成员、分配、初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11553224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com