gpt4 book ai didi

c - 如何在函数 C 编程中打印二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:27:50 25 4
gpt4 key购买 nike

我是二维数组和结构的新手,对指针的了解有限。我的问题是显示功能只显示地址。我不知道我的代码的哪一部分是错误的或缺失的。你能给我建议来解决它或想法吗?谢谢!

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <assert.h>


struct Inventory
{
char name[100];
float latestCost;
int stock;
int sold;
};
struct Inventory *getInfo(void);
void display(struct Inventory *items[][4], int n);
main()
{
char select;
struct Inventory items[10][4];
int i,n,j, *ptr;

printf("\nEnter how many items in the inventory:\n");
scanf("%d", &n);

ptr = malloc(sizeof(struct Inventory));

for(i= 0; i < n; i++)
{
items[i][4] = *getInfo();
}
display(&items,n);

getch();
}
struct Inventory *getInfo(void)
{
struct Inventory *items = malloc(sizeof(struct Inventory));
assert(items != NULL);
fflush(stdin);
printf("\nName of the item: \n");
gets(items->name);
printf("\nCost:");
scanf("%f", &items->latestCost);
printf("\nStock:");
scanf("%d", &items->stock);
printf("\nTotal Sold:\n");
scanf("%d", &items->sold);
return items;
}
void display(struct Inventory *items[][4], int n)
{
int i, j;

for(i = 0; i < n; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d\t", items[i][j]);
}
printf("\n");
}

}

最佳答案

这里

void display(struct Inventory *items[][4], int n);

你想要一个指向 4 个 Inventory 的数组的指针,而不是一个指向 Inventory 的二维指针数组,更改为

void display(struct Inventory items[][4], int n)

void display(struct Inventory (*items)[4], int n)

这里

display(&items,n);

你不需要传递地址

display(items,n);

够了


printf("%d\t", items[i][j]);

%d 打印一个整数,使用结构的一些成员:

printf("%d\t", items[i][j].stock);

printf("%d\t", items[i][j].sold);

关于c - 如何在函数 C 编程中打印二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29629443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com