简体   繁体   中英

fill a list of struct in c

I have a problem Im using a list of struct in C, when I add an Item in the list I do this:

nodo *nuevo=(nodo*) malloc (sizeof(nodo));
    char nombre[5]="vd";
    nombre[2]=letra;
    nombre[3]=indice;
    nombre[4]='\0';
    nuevo->siguiente = NULL;
    nuevo->path= path;
    nuevo->nombre= nombre;

this works but in another method when I try to get the values of nombre and path seems like if them are empty ("") but when I Set the values by this way:

nuevo->path= "anyString";
nuevo->nombre= "anyString";

in the other method I can get the values perfectly, any suggestion? the struc nodo is this:

typedef struct{
    char *path;
    char *nombre;
    particion *part;
    struct nodo *siguiente;
}nodo;

and when i save in the list i do this:

 primero=nuevo;

where primero is of type nodo *

and when I try to get the values, I use:

 if(strcmp(aux->nombre,id)==0){
            printf("Value is fine");
            break;
        }

I will apreciate any sugestion or comment, thank to all. Im in Codeblocks in debian.

You have not specified but it appears that char nombre[5] is local and so is on function stack

So if you assign that to nuevo->nombre and use it in another function its going to lead to undefined behavior as stackframe would now be pointing somewhere else

Better approach will be allocate memory to nuevo->nombre with malloc then copy your string into it using strcpy

malloc enough space to store data for each of the pointer in your struct and copy strings to the allocated pointers.

nuevo->path = malloc(strlen(path) + 1);
strcpy(nuevo->path, path);

(and so on for other fields as well)

In the first method you are assigning the chars pointer (nuevo->path and nuevo->nombre) to the char array address, so if the char arrays are local or they value change it will affect your pointers.

In the second method the compiler will allocate memory to your pointer and assign the value to them so you can retrieve the value in any functions.

to make first method works you need to change your code to below sample

    nuevo->path= (char *)malloc(strlen(path)+1);
    strcpy(nuevo->path,path);
    nuevo->nombre= (char *)malloc(strlen(nombre)+1);
    strcpy(nuevo->nombre,nombre);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM