简体   繁体   English

内部包含数组的结构数组

[英]Struct array with array inside it

I have an assignment in my class where I would like to keep my variables in a struct array because I think it would be the most clean way to do it.我在课堂上有一个作业,我想将变量保存在结构数组中,因为我认为这将是最干净的方法。

I drew up this quick drawing in paint just to make it easier to explain我用颜料画了这张快速图只是为了更容易解释结构数组思想

This is just one of the "nodes" in the struct I would like to make the struct so I can duplicate everything after file in the drawing这只是结构中的“节点”之一,我想制作结构,这样我就可以在绘图中的文件之后复制所有内容

not entirely sure how I go about doing this不完全确定我是如何做这件事的

so far I got a struct array that works fine.到目前为止,我得到了一个可以正常工作的结构数组。 But I can't seem to figure out how to get the last row added, and by last row I mean Grocery 1-3, quantity 1-3 and unitprice 1-3.但我似乎无法弄清楚如何添加最后一行,最后一行我的意思是杂货店 1-3、数量 1-3 和单价 1-3。

for my struct I made:对于我制作的结构:
结构

and that part works fine, but still missing the last "node"这部分工作正常,但仍然缺少最后一个“节点”

Below is short example of creating an array of structs inside of a struct in C. I made it a an array of structs in side of a struct, because I thought you might want to customize what each of "Grocery" / "Price" / "UnitPrice" are.下面是在 C 中的结构体内部创建结构体数组的简短示例。我将其设为结构体侧面的结构体数组,因为我认为您可能想要自定义每个“杂货”/“价格”/ “单价”是。

In the code below, I used "malloc" to dynamically allocate an array of structs.在下面的代码中,我使用“malloc”来动态分配结构数组。 This is the "C" style way to dynamically allocate memory.这是动态分配内存的“C”风格方式。 If you are using C++, then you should use "new"如果您使用的是 C++,那么您应该使用“new”

I only assign the first item in the array with [0].我只用 [0] 分配数组中的第一项。 You could assign the others using [1], and [2] indices, respectively.您可以分别使用 [1] 和 [2] 索引分配其他人。

struct Grocery
{
   /* fill in details of Grocery here you could add more than 1 item*/
   int Value;
}

struct Quantity
{
   /* fill in details of Quantity here */
   int Value;
}

struct Unitprice
{
   /* fill in details of Unitprice here */
   int Value;
}

struct file
{
   struct Grocery* groceries;
   int totalGroceries;
   
   struct Quantity* quantities;
   int totalQuantities;
   
   struct Unitprice* unitprices;
   int totalUnitprices;
}

int main()
{
   struct file Table;
   
   Table.totalGroceries = 3
   Table.groceries = (struct Grocery*)malloc(Table.totalGroceries * sizeof(Grocery));
   
   Table.totalQuantities = 3
   Table.quantities = (struct Quantity*)malloc(Table.totalQuantities * sizeof(Quantity));
   
   Table.totalUnitprices = 3
   Table.unitprices = (struct Unitprice*)malloc(Table.totalUnitprices * sizeof(Unitprice));
   
   /* Assign details to groceries here */
   Table.groceries[0].Value = 5;
   
   /* Assign details to Quantity here */
   Table.quantities[0].Value = 5;
   
   /* Assign details to unitprices here */
   Table.unitprices[0].Value = 5;
   
   /* Other logic here */
   
   /* End of program deallocate allocated memory */ 
   free(Table.groceries);
   free(Table.quantities);
   free(Table.unitprices);
}

For more information I recommend you look at this link https://stackoverflow.com/questions/260915/how-can-i-create-a-dynamically-sized-array-of-structs#:~:text=If%20you%20want%20to%20allocate,type%20void%20(%20void*%20) on how to dynamically allocate array of structs in C有关更多信息,我建议您查看此链接https://stackoverflow.com/questions/260915/how-can-i-create-a-dynamically-sized-array-of-structs#:~:text=If%20you %20want%20to%20allocate,type%20void%20(%20void*%20)关于如何在 C 中动态分配结构数组

While your drawing and your description are in conflict to a certain extent, it appears you want to be able store data for a number of Items or Files where each item coordinates a grocery value, a quantity value and a unitprice values (similar to what you would use for the basis of an inventory system).虽然您的绘图和您的描述是在冲突在一定程度上,它似乎你想了许多项目文件的能够存储数据,其中每个项目协调一个grocery值, quantity值和unitprice值(类似于您将用作库存系统的基础)。

From your drawing, your Filenr struct member doesn't make much sense.从您的绘图中,您的Filenr结构成员没有多大意义。 Why?为什么? If your base Item struct coordinates grocery , quantity , and unitprice , then unless the Filenr provides an additional unique bit of information that is part of that grocery , quantity , and unitprice , then it can simply be omitted and you can use its index to describe the grocery , quantity , and unitprice .如果你的基础Item结构坐标groceryquantityunitprice ,那么除非Filenr提供的信息的附加唯一的位即是,部分groceryquantityunitprice ,那么它可以简单地省略,你可以使用它的索引来形容在groceryquantityunitprice

Further, being of type char , its value would be limited to one of 256 values ( -128 - 127 ).此外,作为char类型,其值将被限制为 256 个值之一( -128 - 127 )。 If you are actually considering that to be a printable characters, then your range of values is reduced to just 96 printable characters.如果您实际上将其视为可打印字符,那么您的值范围将减少到仅 96 个可打印字符。

You define your struct based on the data you have.您可以根据您拥有的数据定义结构。 If Filenr is a piece of data that is part of your input and is associated with grocery , quantity , and unitprice , then add it to your struct as a member.如果Filenr是一块数据的是你的输入的一部分,并且相关联groceryquantity ,以及unitprice ,然后将其添加到你的结构作为成员。 If it is just something you are using to refer to a unique struct, then it isn't needed -- UNLESS -- you can have two struct with the exact same values in grocery , quantity , and unitprice and you are using Filenr to disambiguate between two otherwise identical struct.如果您使用的是指一种独特的结构,则不需要它只是东西-除非-你可以有两种结构在完全相同的值groceryquantityunitprice和你正在使用Filenr消除歧义在两个其他相同的结构之间。 Otherwise, omit it and use an index.否则,省略它并使用索引。

Without it, you would simply create an array of your structs.没有它,您只需创建一个结构数组。 That would allow you to be able to sort, query and sum by any of the member values.这将使您能够按任何成员值进行排序、查询和求和。 A trivial implementation that prints the stored (made-up) values would be:打印存储(虚构)值的简单实现是:

#include <stdio.h>

typedef struct {                /* your struct using a typedef for convenience */
    int grocery, quantity;
    double unitprice;
} item;

/* simple function to output all n struct in any array of item */
void prn_items (item *items, size_t n)
{
    for (size_t i = 0; i < n; i++)
        printf ("\nFilenr[%2zu]:\n grocery   : %d\n quantity  : %d\n unitprice : %0.4f\n",
                i, items[i].grocery, items[i].quantity, items[i].unitprice);
}

int main (void) {
    
    item files[] = {{ 31756, 22, 1.3405 },      /* made-up example data for array */
                    {  7818, 83, 2.4722 },
                    { 17920, 63, 1.3795 },
                    {  2937, 32, 2.8648 },
                    {  8423, 44, 2.6031 }};
    size_t n = sizeof files / sizeof *files;    /* number of elements in array */
    
    prn_items (files, n);                       /* output all struct */
}

Example Use/Output示例使用/输出

Running the program simply outputs all stored struct values coordinated by index as the Filenr :运行程序简单地将所有存储的由索引协调的结构值输出为Filenr

$ ./bin/grocerystruct

Filenr[ 0]:
 grocery   : 31756
 quantity  : 22
 unitprice : 1.3405

Filenr[ 1]:
 grocery   : 7818
 quantity  : 83
 unitprice : 2.4722

Filenr[ 2]:
 grocery   : 17920
 quantity  : 63
 unitprice : 1.3795

Filenr[ 3]:
 grocery   : 2937
 quantity  : 32
 unitprice : 2.8648

Filenr[ 4]:
 grocery   : 8423
 quantity  : 44
 unitprice : 2.6031

Now if your intent was to save each of the struct in a separate file, you could simply create an output filename with sprintf() that contains a unique suffix (or prefix) based on the index.现在,如果您打算将每个结构保存在单独的文件中,您可以简单地使用sprintf()创建一个输出文件名,该文件名包含基于索引的唯一后缀(或前缀)。

If you really want a single char and Filenr as part of your struct, you can simply include it by adding it back as a member, eg如果你真的想要一个单一的charFilenr作为你结构的一部分,你可以简单地通过将它作为成员添加回来来包含它,例如

typedef struct {                /* your struct using a typedef for convenience */
    char Filenr;
    int grocery, quantity;
    double unitprice;
} item;

Adjust the reminder of the code to handle the additional member.调整代码提醒处理新增成员。

Lastly, you don't want to use a floating-point number related to price.最后,您不想使用与价格相关的浮点数 (companies get mad when you lose money due to rounding error). (当你因为舍入错误而亏钱时,公司会生气)。 Better to use an integer value multiplied accordingly to ensure rounding error doesn't occur.最好使用相应乘以的整数值以确保不会发生舍入错误。 You can search "floating point type for money" and find a wealth of additional information on that topic.您可以搜索“货币的浮点类型”并找到有关该主题的大量附加信息。

Look things over and let me know if you have further questions.仔细检查一下,如果您还有其他问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM