【问题标题】:Implementation dynamic allocation of structure in C在C中实现结构的动态分配
【发布时间】:2019-10-17 13:13:45
【问题描述】:

谁能告诉我为什么我的代码不起作用? 它可以正确编译,但在执行过程中,它会停止给出错误消息。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct book
{
    char cName[100];
    float fPrice;
};
struct book *ptr;

void display(int j)
{
    int i=0;
    ptr = ptr - j;
    while(i<j)
    {
        printf("Book name: %s\n",ptr->cName);
        printf("Price: %f\n\n",ptr->fPrice);
        ptr++;
        i++;
    }
}
int main()
{
    int i,n;
    printf("How many entries do you want to make: ");
    scanf("%d",&n);

    ptr = (struct book*)malloc(n*sizeof(struct book));
    for(i=0;i<n;i++)
    {
        printf("Enter the Name: ");
        scanf("%s",ptr->cName);
        printf("Enter price: ");
        scanf("%f",ptr->fPrice);
        ptr++;  
    }
    display(n);
    return 0;
}

免责声明:我是 C 的新手,如果我的编码伤害了你的眼睛,我真诚地提前道歉。只是想了解程序而不是快速完成它。

【问题讨论】:

  • scanf("%f",ptr-&gt;fPrice); 行应该是scanf("%f",&amp;ptr-&gt;fPrice); 函数scanf 需要变量的地址。在前一行中,数组 decays 指向一个指针,因此不需要&amp;
  • 不要修改ptr——你需要保留malloc()返回的值,以便以后可以释放内存。在main()display() 中都使用ptr[i](或ptr[i].cName 等)。最好将ptrn 传递给display() — 尽可能避免使用全局变量。 (如所写,您需要在main() 中写入free(ptr - n) 以发布数据。这不是惯用的C。)此外,您可以(应该)是系统的;你在main() 中使用for 循环,在display() 中没有理由不这样做。
  • ...虽然你说它编译正确,但有一个编译器警告。

标签: c syntax


【解决方案1】:

这里是:

scanf("%f",ptr->fPrice);

必须是这样的:

scanf("%f",&ptr->fPrice); // with a "&"

因为你想传递一个指向float的指针。


另一方面,请始终注意编译器的警告。他们可以指出通常是错误的代码模式。例如,您的代码可能会在 'scanf' : format string '%f' requires an argument of type 'float *', but variadic argument 1 has type 'double' 的行中引起警告。

【讨论】:

  • 我同意这个建议,但为什么指针算术“错误”?这是不寻常的,而且是特殊的而不是惯用的,但是……到底出了什么问题?
  • 更正&amp; 可修复输出。虽然非常规,但指针的使用并没有错。
  • 是的,它现在也对我有用。似乎错误是我的一部分。感谢您指出。
  • 您可能会注意到,书名必须只有一个单词——在标题遇到问题时输入“金银岛”——有很多方法可以解决这个问题,但需要注意。
猜你喜欢
  • 2015-10-20
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 2015-07-23
  • 2014-08-22
  • 2012-03-10
  • 1970-01-01
  • 2021-12-03
相关资源
最近更新 更多