Cipher
Cipher

Reputation: 87

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. I want to know how to declare and use this array. Also how can i save the data i need inside of it.

Upvotes: 0

Views: 44

Answers (2)

Bean Taxi
Bean Taxi

Reputation: 1261

#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

$ ./a.out 
3
4
5

Upvotes: 1

sergzemsk
sergzemsk

Reputation: 172

If you want to store products id inside this struct declare array

int products_id[MAX_PRODUCTS_ID];

Pointer *products_id can store an address of outside memory (that you should manage by yourself)

Upvotes: 0

Related Questions