Home > database >  How should I use an array of pointers of structs in C in my code below?
How should I use an array of pointers of structs in C in my code below?

Time:06-19

I have a more complex project, I simplified (as much as I could) my problem into the code you can see here.

I suspect the problem is around the function create_B() in file B.c, and/or when I call this function from the file A.c . Or maybe my x and y also should be pointers? As you can tell I am just learning C programming, any help/explanation would be greatly appreciated.

B.h:

#ifndef B_H
#define B_H

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

typedef struct B B;
typedef B *B_ptr;

struct B
{
    int x;
    int y;
};

B_ptr create_B(int x, int y);

#endif

B.c:

#include "B.h"

B_ptr create_B(int x, int y) {
    B_ptr b = (B_ptr)malloc(sizeof(B));
    b->x;
    b->y;
    return b;
}

A.h:

#ifndef A_H
#define A_H

#include "B.h"

typedef struct A A;
typedef A *A_ptr;

struct A
{
    B_ptr *list_of_10_pointers;
};

A_ptr create_A();

#endif

A.c:

#include "A.h"

A_ptr create_A()
{
    A_ptr a = (A_ptr)malloc(sizeof(A));
    if (!a)
        return NULL;

    B_ptr *list = (B_ptr *)malloc(10 * sizeof(B_ptr));
    if (!list)
        return NULL;
    a->list_of_10_pointers = list;

    for (size_t i = 0; i < 10; i  )
    {
        // list[i] = (B_ptr)malloc(sizeof(B));
        list[i] = create_B(i 1, i 2);
    }

    return a;
}

Main.c:

#include <stdio.h>

#include "A.h"

int main(int argc, char **argv)
{
    A_ptr a = create_A();

    for (size_t i = 0; i < 10; i  )
    {
        printf("x=%d\n", a->list_of_10_pointers[i]->x);
        printf("y=%d\n", a->list_of_10_pointers[i]->y);
    }
    return 0;
}

To compile: gcc Main.c A.c B.c -o out

Output:

x=0
y=0
x=0
y=0
.
.
.
x=0
y=0

CodePudding user response:

Compiling gives these warnings:

$ gcc Main.c A.c B.c -o out
B.c:5:8: warning: expression result unused [-Wunused-value]
    b->x;
    ~  ^
B.c:6:8: warning: expression result unused [-Wunused-value]
    b->y;
    ~  ^
2 warnings generated.

That leads almost directly to changing B.c to this:

#include "B.h"

B_ptr create_B(int x, int y) {
    B_ptr b = (B_ptr)malloc(sizeof(B));
    b->x = x;
    b->y = y;
    return b;
}

Then the output becomes:

$ ./out
x=1
y=2
x=2
y=3
x=3
y=4
x=4
y=5
x=5
y=6
x=6
y=7
x=7
y=8
x=8
y=9
x=9
y=10
x=10
y=11
  • Related