![]() |
| ||
| Printing struct from linked list I have a linked list of structs, with each struct having a char* and an int. When I try to print the list I get a seg fault. If I just print the int however it works. What am I doing wrong so the char* won't print? printf("%s %d\n", p->name, p->age); Thanks. |
| ||
| Re: Printing struct from linked list A segmentation fault occurs when a program tries to access memory location that is not allow to play with. My guess is that your char* is pointing to some wrong memory location. Maybe you haven't initialized to point to a string. |
| ||
| Re: Printing struct from linked list After many tries I still have not figured out the problem. I no longer have a seg fault, but now when I try to print the list I get "garbage" values for the strings and the correct values for the ints. I have no idea why I am getting correct values for ints and not char *. Any ideas? //mp3.h //mp3.c Thanks. |
| ||
| Re: Printing struct from linked list Consider this: scanf("%s", &tempString);The second argument to [icode]scanf[icode] is of the wrong type. temp->artistis a dangling pointer -- you need to allocate memory for it. You don't copy the string with assignment, look into strcpy. |
| ||
| Re: Printing struct from linked list Thanks for the response. I tried strcpy before, but that lead me to a seg fault. I'm sorry, how would I go about allocating memory for the pointer? |
| ||
| Re: Printing struct from linked list Either make them arrays in the structure, or after you've read a string into tempString, malloc(strlen(tempString)+1)to the pointer. |
| ||
| Re: Printing struct from linked list scanf("%s", &tempString);Is this what you mean? I would make them arrays in the structure but the assignment specifies that they have to be char*s. |
| ||
| Re: Printing struct from linked list Remove the & operator, tempString as such must be used in that scanf (tempString is a pointer, hence no need for &). scanf("%s", &tempString);Then allocate memory before copying.temp->artist = (char*) malloc(strlen(tempString)+1);You may want to check that malloc() actually succeeded, (i.e NULL != temp->artist). Also remember to free() all the malloc'ed memory at some point. |
| ||
| Re: Printing struct from linked list Thank you so much mitrmkar - problem solved. |
| All times are GMT -4. The time now is 1:49 pm. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC