简体   繁体   English

内部带有指针的结构是一个数组(C)

[英]struct with a pointer inside that is an array (C)

I have the following struct:我有以下结构:

struct card{
  int id;
  int *products_id;
  int number;}

The thing that the pointer products_id must be an array because i need to save different products id for the same id.指针 products_id 必须是一个数组,因为我需要为同一个 id 保存不同的产品 id。 I want to know how to declare and use this array.我想知道如何声明和使用这个数组。 Also how can i save the data i need inside of it.另外,我怎样才能在其中保存我需要的数据。

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

struct card{
  int id;
  int *products_id;
  int number;
};


int main ()
{
    struct card c;
    c.products_id = (int*)malloc(sizeof(int)*3); // 3 ints
    c.products_id[0] = 3;
    c.products_id[1] = 4;
    c.products_id[2] = 5;

    for (int i=0; i<3; ++i)
    {
        printf("%d\n", c.products_id[i]);
    }
}

Output Output

$ ./a.out 
3
4
5

If you want to store products id inside this struct declare array如果你想在这个结构声明数组中存储产品 ID

int products_id[MAX_PRODUCTS_ID];

Pointer *products_id can store an address of outside memory (that you should manage by yourself)指针*products_id可以存储 memory 以外的地址(请自行管理)

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

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