I have a string which I need to pass to a function like below.
scanf("%s%d",&name,&telno);
addatend(telno,name);
where
char name[MAX];
I am getting the following warning :
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[50]’ [-Wformat]
I did try to do changes like having one more char pointer and point to name. But the warning stays.
In the function I have strcpy
strcpy(addnode->name,name1);
This is coping the name from main to the name in the structure addnode. But there is a segmentation fault at this line.
I tried to check in splint (did not have any issues at this line) and valgrind but could not identify my mistake. Hence came here for help. Thanks in advance..
The code:
typedef struct Mystruct{
char *name;
int telno;
struct Mystruct *nextp;
}data;
void addatend(int telno1, char* name1)
{
data *addnode, *previousnode;
addnode = malloc (sizeof(data));
if(addnode == NULL)
{
printf("Memory allocation failed...Exiting");
exit(0);
}
strcpy(addnode->name,name1); //error Part of the code.
When reading a string with
scanf, the array is passed to the function as a pointer, so you don’t need the address-of operator&.Regarding your second problem… You need to allocate memory for the destination you copy to as well. Either use
mallocagain (usingstrlen(...) + 1, the+1for the string terminator) before thestrcpy, or usestrdupwhich allocates and copies the string: