【问题标题】:C pointers as struct members, allocation, initializationC 指针作为结构成员、分配、初始化
【发布时间】:2012-07-18 04:30:50
【问题描述】:

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

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

【问题讨论】:

  • 您没有发布 NewQuotient 的代码。您应该发布整个相关代码。
  • 抱歉,我以为我在里面,现在已经添加了。
  • 缺少 struct term 的代码。您能否发布所有相关代码,以便我可以编译/尝试它。
  • 我添加了结构和主要功能,我想这就是一切。

标签: c pointers structure dynamic-allocation


【解决方案1】:

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

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

【讨论】:

  • 这是其中的一部分,导致核心转储。不过,scanf 语句的行为仍然很糟糕。
  • 您必须比“表现不佳”或“工作不正常”做得更好才能获得有用的答案
  • 确实如此,它被重新编译并使用相同的输入运行并产生相同的输出。
  • 所以运行的时候连“输入系数”都不输出?你的主要职能是什么?
【解决方案2】:

当使用scanf时,你通常希望得到Return键以及数字。

你有:

scanf("%d", &temp.numerator);

你真的想要:

scanf("%d\n", &temp.numerator);

【讨论】:

  • 当我自己运行它时,我发现scanf("\n%d", %temp.numerator); 可以工作,而将\n 放在最后却不行。
  • 无论采用哪种方式,只要确保捕获用户输入的所有字符即可。[Return] 不会被 %d 捕获,但需要在某个地方/以某种方式捕获。
【解决方案3】:

您还应该使用验证来确保只输入数字,否则您会得到古怪的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多