如何在函数C编程中打印2D数组

时间:2015-04-14 14:03:03

标签: c arrays

我是2D数组,结构的新手,对指针知之甚少。我的问题是显示功能只显示地址。我不知道我的代码的哪一部分是错误的或遗漏的。你可以给我一些建议来解决它或想法吗?谢谢!

#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");
    }

}

1 个答案:

答案 0 :(得分:2)

下面

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

你想要一个指向4 Inventory的数组的指针,而不是指向Inventory的2d指针数组,改为

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);