I have a problem with my code when I'm trying to store and print a string in a struct.
I have extracted the essential parts of the code here:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct post
{
char name[30];
int tel;
struct post *next;
};
typedef struct post Post;
Post *head = NULL;
Post *current;
Post* CreateList(char tempname[30], int temptel);
Post* CreateList(char tempname[30], int temptel)
{
Post *ptr = (Post*)malloc(sizeof(Post));
strcpy(ptr->name, tempname);
ptr->tel = temptel;
ptr->next = NULL;
printf("\n creating list with headnode as [%s]\n",tempname);
head = current = ptr;
return ptr;
}
int main()
{
char tempname[30];
int temptel;
Post * ptr;
printf("[Name] [Number] = ");
scanf("%s %d", &tempname[30], &temptel);
CreateList(tempname, temptel);
}
In the main you are supposed to insert a name and number and in CreateList it creates the first node of a linked list. When I'm trying to print the string with the name some garbage appears but the number is printed all fine.
I suspect that tempname is not really sent from main to CreateList even though i tried to send it as an argument in the function. I have tried to print the name stored in the struct as well:
printf("\n creating list with headnode as [%s]\n",ptr->name);
but this also fails.
So the problem appears when I'm trying to print the name but since I've tried really many ways of printing it (with strcpy(), strncat(), strdup()) I start to suspect that i'm never actually storing the string in the ptr->name. So I'm either printing it wrong or storing it wrong.
I would really appreciate any help or hints towards a solution on this problem! Thanks in advance.