简体   繁体   English

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

[英]How to print a 2D array in a Function C Programming

I'm new to 2D arrays, structs and have a limited knowledge about pointers. 我是2D数组,结构的新手,对指针的知识有限。 My problem is that the display function only displays addresses. 我的问题是显示功能仅显示地址。 i dont know which part of my code is wrong or missing. 我不知道我的代码的哪一部分是错误的或丢失的。 can you give me suggestions to fix it or ideas? 您能给我一些建议来解决它或想法吗? Thanks! 谢谢!

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

}

Here 这里

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

you want a pointer to an array of 4 Inventory s, not a 2d array of pointers to Inventory , change to 您想要一个指向4个Inventory的数组的指针,而不是指向Inventory的2d指针的数组,请更改为

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

or 要么

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

Here 这里

display(&items,n);

you don't need to pass the address 您不需要通过地址

display(items,n);

is enough 足够


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

%d prints an integer, use some member of the struct: %d打印一个整数,使用该结构的某些成员:

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

or 要么

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

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

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