【问题标题】:How to add items to a 2D "ArrayList" in C and search for items in it如何将项目添加到 C 中的二维“ArrayList”并在其中搜索项目
【发布时间】:2019-10-22 13:00:53
【问题描述】:
struct item {
    char name[100];
    double price;
} item;


char name[100];
int shelf;
int slot;
float price;
int NumOfShelves = 50
int NumOfSlotsPerShelf = 2
struct item *arrayl = (int *) malloc(NumOfShelves * NumOfSlotsPerShelf * sizeof(int));

//这是我的“数组列表”^ 我认为

printf("Add an item name);
scanf("%s", &name);
printf("Add an item price);
scanf("%f", &price);
printf("Add the shelf number of the item");
scanf("%d", &shelf);
printf("Add the slot number");
scanf("%d", &slot);

//在这一行。如何将项目添加到我的阵列中的该插槽和架子?

printf("Search for an item by first giving the shelf number:");
scanf("%d", &slot);
printf("Search by giving the slot number");
scanf("%d", &slot);

//如果arrayl包含位置

//打印该位置的商品名称和价格

else {
printf("None")
return 0;
}

【问题讨论】:

  • 您的问题不清楚。你想要struct item 的数组吗?而且我在这里看不到任何二维数组...请阅读此内容:How to Ask 然后edit 您的问题并澄清。
  • int *arrayl = (int *) malloc(NumOfShelves * NumOfSlotsPerShelf * sizeof(int));这不是数组吗?是的,我想要一个结构项目数组。我该怎么办?
  • 是的,这或多或少是int 的数组,但不是struct items 的数组。请参阅下面的答案。
  • 明确一点,int *arrayl = (int *) malloc(NumOfShelves * NumOfSlotsPerShelf * sizeof(int)); 这不是一个数组吗? 不,它是指向内存中特定位置的指针的集合。 int array1[10][20] = {0};C 数组的一个示例。两者都允许使用索引符号来访问集合的元素,但只有一个是实际数组。
  • @johnjacob 请不要对已回答的问题进行重大更改。它使给出的答案无效,从而破坏了整个 QA 想法。如果您在使用答案中的建议后仍有问题,则应改写一个新问题。

标签: c


【解决方案1】:

您的数组类型错误。使用

struct item *arrayl = malloc(NumOfShelves * NumOfSlotsPerShelf * sizeof *array1);
^^^^^^^^^^^                                                              ^^^^^^

那么你只需这样做:

array1[shelf * NumOfSlotsPerShelf + slot].price = price;

名称类似,但您需要 strcpy 而不是 =

strcpy(array1[shelf * NumOfSlotsPerShelf + slot].name, name);

malloc 的另一种做法是:

 int NumOfShelves = 50;
 int NumOfSlotsPerShelf = 2;
 struct item (*array1)[NumOfSlotsPerShelf] = malloc(NumOfShelves * sizeof *array1);

这将允许您在数组中写入项目,例如:

array1[shelf][slot].price = price;
strcpy(array1[shelf][slot].name, name);

注意

使用malloc 表示数组中的所有项最初都未初始化。使用calloc 可能是一个更好的主意,以便所有项目都初始化为零。

【讨论】:

  • 索引应该是shelf * NumOfSlotsPerShelf + slot,不是吗?
  • 嗨。非常感谢!我决定使用第二个 Malloc,因为它提供了一种更简单的方式来搜索项目。我看到的唯一问题是我无法在第二个 malloc 上使用您建议的第一种方法(关于将项目添加到数组中)。我该怎么做呢?
  • @johnjacob 答案显示了如何为两种类型的 malloc 写入数组中的项目。
  • @johnjacob 如果您要问如何更改内存以允许更多项目已经被malloc'ed,realloc 是你会怎么做那。但请注意,使用它的一些微妙之处:How to use realloc.
  • 你必须改变'.' to -> 我相信
猜你喜欢
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多