user1315621
user1315621

Reputation: 3412

Strings dynamic allocation in C

I'm working with C. Can you tell me if this is the right way to allocate memory for a struct which contains a string?

struct _TipoLista {
    char info[10];
    struct _TipoLista *next;
};
typedef struct _TipoLista *TipoLista;

...

TipoLista el;
el = malloc(sizeof(TipoLista));

If a try to create a list in this way, I always get errors when I try to insert the 2nd element while. However, if I change "info" from char[10] to an int my code always works.

Upvotes: 2

Views: 123

Answers (5)

Exceptyon
Exceptyon

Reputation: 1582

Hope this can be useful:

typedef struct {
    char info[10];
    struct _TipoLista *next;
} TipoLista;


TipoLista* construct_lista()
{
   TipoLista* ret = malloc(sizeof(TipoLista));
   ret->next = NULL;
   return ret;
}

void destruct_lista(TipoLista* lista)
{
    TipoLista* next;
    while (lista != NULL)
    {
         next = lista->next;
         free(lista);
         lista=next;
    }
}


void insert_into_list(TipoLista* lista, char* element)
{
    while (lista->next != NULL)
         lista = lista->next;

    lista->next = construct_lista();
    strcpy(lista->next->info, element);
}

Upvotes: 0

Adit Ya
Adit Ya

Reputation: 769

You are trying to do a typedef i.e., an alias for the strucuture. Typedef in turn means that "from this point onwards *struct _TipoLista* will be called as *TipoLista "

If you want to have a linked list of type "struct _TipoLista", then this could help.

struct _TipoLista {
    char info[10];
    struct _TipoLista *next;
};
typedef struct _TipoLista TipoLista;

int main()
{
TipoLista *Tptr = malloc(sizeof(TipoLista) );
/** Rest is history */
}

Upvotes: 0

doptimusprime
doptimusprime

Reputation: 9415

You should try the following

el = malloc(sizeof(struct _TipoLista));

Or define a typedef for this structure.

Upvotes: 0

KARTHIK BHAT
KARTHIK BHAT

Reputation: 1420

el = malloc(sizeof(*el));

or

el = malloc(sizeof(struct _TipoLista));

or initializing while declaring the struct

struct _TipoLista {
  char info[10];
  struct _TipoLista *next;
}obj1;

In the first two cases it's dynamic memory allocation 3rd is static memory allocation

Upvotes: 2

tristan
tristan

Reputation: 4322

   el = malloc(sizeof(*el));

TipoLista has size of a pointer so that's not what you really want.

Upvotes: 1

Related Questions