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

标签 c arrays

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

#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/

相关文章:

C while循环无限循环EOF不起作用

c - char** 是指向 C 中字符串数组的指针吗?

jquery - 设置数组中文本的格式?

关于返回声明的困惑

c - (作业)如何将一个指针中的 C 字符串放入另一个指针的内存地址中?

arrays - 将工作表范围分配给数组

php - 如何更改 PHP 中特定关联数组的值?

java - 具有非数字键的 PHP 数组的 Java 等价物是什么?

c - C 中的 For 循环出现奇怪的错误

c - C语言图案打印