strcpy () in struct string

1

I have a struct Time that has a char name[30] vector, the problem starts when I try to copy a value to this string with the function strcpy() , it follows the code of stuct :

typedef struct Time{
  char name[30];
  int pnts;
  int vit, emp, der;
  int gf, gt;

  struct Time *next;
  struct Time *prev;
}time;

and here is the function that implements s trcpy() :

void addTime(campeonato *c, char name[]){
  time t;
  strcpy(t.name, name);
  t.next = NULL;
  t.pnts = t.vit = t.emp = t.der = t.gt = t.gf = 0;

  if(c->first == NULL){
    c->first =  &t;
    t.prev = NULL;
  } else {
    time *p = c->first;
    while(p->next != NULL){
        p = p->next;
    }
    p->next = &t;
    t.prev = p;
  }
}

The main() looks like this:

campeonato c;
createCamp(&c, "Brasileirao");
addTime(&c, "Palmeiras");
time *t = c.first;

printf("%s", t->name);

return 0;

The value of print for t->name is always garbage.

    
asked by anonymous 31.10.2016 / 12:01

1 answer

2

I made a minimal, complete, and verifiable example. I have not tried to make cute or improve the other problems of the code, but this is solved. The team object is being created locally in the addTime() function, so in the stack , when it exits the function, it no longer has access to the object, so it can not access it. The correct one in this case is to either allocate the object to main() and pass a pointer to it, or allocate in the heap to survive the end of the function. More or less like this:

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

typedef struct Time{
  char name[30];
  int pnts;
  int vit, emp, der;
  int gf, gt;

  struct Time *next;
  struct Time *prev;
} time;

typedef struct campeonato { time *first; } campeonato;

void addTime(campeonato *c, char name[]) {
    time *t = malloc(sizeof(time));
    strcpy(t->name, name);
    t->next = NULL;
    t->pnts = t->vit = t->emp = t->der = t->gt = t->gf = 0;
    if (c->first == NULL) {
        c->first =  t;
        t->prev = NULL;
    } else {
        time *p = c->first;
        while (p->next != NULL) {
            p = p->next;
        }
        p->next = t;
        t->prev = p;
    }
}

int main(void) {
    campeonato c = { .first = NULL };
    addTime(&c, "Santos");
    time *t = c.first;
    printf("%s", t->name);
    return 0;
}

See working on ideone and on CodingGround .

    
31.10.2016 / 12:32