Problems with dynamic allocation and struct

Asked

Viewed 208 times

1

I intend to create a struct where there will be a vector of structs... The way I thought of doing it was kind of like this:

typedef struct{
    char *teste_str;
    int teste_int;
}TESTE_A;

typedef struct{
    TESTE_A **t;
}TESTE_B;

TESTE_B teste;

int main(void)
{
    teste.t = (TESTE_A**)malloc(3 * sizeof(TESTE_A*));
    teste.t[0]->teste_int = 25;
    printf("%d\n", teste.t[0]->teste_int);
    return 0;
}

But why member value is not changed and program error?

  • The first thing you need to decide is whether to do it in C or C++. What happens when you try to compile? The code looks confusing. I don’t know what the point is, but there seems to be things in there that shouldn’t be.

1 answer

1


I have considered that you are wanting to do C. The biggest problem is the pointer t which makes no sense. Actually the names are pretty bad, the code is incomplete and doesn’t seem to make any sense.

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

typedef struct {
    char *teste_str;
    int teste_int;
} TesteA;

typedef struct {
    TesteA *t;
} TesteB;

int main(void) {
    TesteB teste;
    teste.t = malloc(3 * sizeof(TesteA));
    teste.t[0].teste_int = 25;
    printf("%d\n", teste.t[0].teste_int);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you very much, I really meant to do it in C... I’m sorry about the code, it’s just that I don’t have anything in mind, I just wanted to know how to do it. But I understood my mistake, thank you!

  • Now you can vote on everything on the site. See the [tour].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.