且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在'{'标记之前的预期表达式

更新时间:2023-01-07 19:11:50

您无法在运行时初始化类似的结构。如果你使用常量值,那么你可以让编译器通过编码来设置它:

You cannot initialise a structure like that at run time. If you are using constant values then you can get the compiler to set it up by coding:
struct item_info
{
      char itemname[15];
      int quantity;
      float retail;
      float wholesale;
      //int quatityonorder;
}item[NOOFITEM] =
{
    {"rice",10,40,30},
    {"sugar",10,40,30},
    {"soap",10,40,30}
};



但是如果要在运行时分配值,则必须手动执行以下操作:


But if you want to assign values at run time then you have to do it manually like:

strcpy(item[0].itemname, "rice");
item[0].quantity = 10;
item[0].retail = 40;
item[0].wholesale = 30;


如果你改变它所以它应该编译,但它不是***的方式

if you change it so it should compile, but it is not the best way
struct item_info
{
      char *itemname;
      int quantity;
...





你遇到的问题是itemname只是一个指针,你需要分配并释放它。并以某种方式管理它。



我会写一个Setter





You have than the problem that itemname is only a pointer and you need to alloc and free it. And manage it somehow.

I would write an "Setter"

Set(struct *item_info, char*name, ...)
{
 strncpy( item_info->name, sizeof(item_info->name), name);//check length!!!

...
}