Reputation: 407
I have function which gets some data from the user, creates a struct using them and adds the struct to a linked list. but it does not save data to the linked list:
typedef struct contact Contact;
typedef Contact *ContactPtr;
int main(){
ContactPtr starPtr;
addContact(starPtr);
printf("## %s", starPtr->firstName);
return 0;
}
void addContact(ContactPtr sPtr){
printf("\n FF:\n");
ContactPtr newPtr;
ContactPtr prevPtr;
ContactPtr currentPtr;
newPtr = malloc(sizeof(Contact));
char fN[20];
char sN[20];
char phN[12];
scanf("%s", &fN);
scanf("%s", &sN);
scanf("%s", &phN);
if (newPtr!=NULL){
strcpy(newPtr->firstName, fN);
strcpy(newPtr->surName, sN);
strcpy(newPtr->phoneNo, phN);
newPtr->next=NULL;
prevPtr = NULL;
currentPtr=sPtr;
while(currentPtr!=NULL){
prevPtr=currentPtr;
currentPtr=currentPtr->next;
}
if(prevPtr==NULL){
printf("!!@");
newPtr->next=sPtr;
sPtr=newPtr;
}
else{
prevPtr->next=newPtr;
newPtr->next=currentPtr;
}
}
else{
printf("$$WRONG");
}
}
Program returns null for starPtr->firstName
.
Is this problem for the function or the linked list? and is it pointing to the right value?
Upvotes: 1
Views: 87
Reputation: 12047
In main
, you have:
ContactPtr starPtr;
addContact(starPtr);
And addContact
is defined as:
void addContact(ContactPtr sPtr){
There is no way how addContact
could modify startPtr
, that's why it is never pointing to anything useful.
If it would be C++, you could change your code to:
void addContact(ContactPtr& sPtr){
With this, you are passing a reference to startPtr
, and it can be modified inside addContact
.
But if it is C, you have to use a pointer to a pointer, like
void addContact(ContactPtr* sPtr){
Inside addContact
, replace sPtr
with *sPtr
.
Change main
like this:
addContact(&starPtr);
Upvotes: 2