Home > Back-end >  How to input and output values from an array of struct pointers in C
How to input and output values from an array of struct pointers in C

Time:08-17

I am trying to create an array of struct b pointers.

I do not know what the correct syntax is to create such a structure.

This is a simplified version of what I am doing in a larger project... to create malloc, therefore I cannot use malloc.

#include <stdio.h>

struct a {
    int val1;
    int val2;
} a;

struct b {
   struct a * next;

   int val1;
   int val2;
} b;
struct b * listOfB[3];



int main() {
    struct a * valueA = {1, 2};

    listOfB[0] = {valueA, 1, 2}; // assign value
    printf("%u\n", listOfB[0]->next->val1); // access value
}

CodePudding user response:

If you want to do it this way you need to use compound literals

int main() {
    struct a *valueA = &(struct a){1, 2};

    listOfB[0] = &(struct b){valueA, 1, 2}; 
    printf("%u\n", listOfB[0]->next->val1); 
}

https://godbolt.org/z/4P6jvsGeY

CodePudding user response:

Please allocate the memory for the pointers to use them.

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

      struct a{
      int val1;
      int val2;
      } a;
    
struct b {
      struct a * next;
      int val1;
      int val2;
      } b;

struct b *listOfB[3];

int main() {
        struct a * valueA;
        valueA = malloc(sizeof(struct a));

        valueA->val1 = 1;
        valueA->val2 = 2;

        listOfB[0] = (struct b *)malloc(sizeof(struct b));

        listOfB[0]->next = valueA;
        listOfB[0]->val1 = 1;
        listOfB[0]->val2 = 2; // assign value

        printf("%d\n", listOfB[0]->next->val1); // access value

        return 0;
}
  • Related