Reputation: 15
I am trying to make an array of pointer pointers to point in an stuct. until now I have the following code done
#include <stdlib.h>
typedef struct ID{
char firstName[21];
char lastName[21];
char phoneNumber[11];
}ID;
int main(int argc, char *argv[]) {
int answere,i=0;
printf("******* WELCOME TO PHONEBOOK **********\n\n\n");
printf("***************************************\n");
printf("* MENU *\n");
printf("* *\n");
printf("* 1.Add New 2.Print list 3.Exit *\n\n");
printf("***************************************\n\n");
ID* ptr=(int*)malloc(21*sizeof(ID));
do
{
printf("Please select (1, 2 or 3): ");
scanf("%d",&answere);
if(answere!=1 && answere!=2 && answere!=3)
{
printf("//...Error...\\ please give me a correct answere: ");
}
if(answere == 1)
{
i++;
addNew(&ptr,i);
}
else if(answere==2)
{
PrintList(&ptr,i);
}
}while(answere!=3);
return 0;
}
so the ptr array gonna be each time a new user and I want it to max out at 3 users the code for adding a new user is the following
ID addNew(ID *ptr,int i){
char fname,lname,phone;
if(i<3)
{
int l;
for (l=1;l<=3;l++)
{
ID user;
ptr[l] = user;
printf("enter the first name: ");
scanf("%s",&fname);
*ptr->firstName= fname;
printf("enter the last name: ");
scanf("%s",&lname);
*ptr->lastName = lname;
printf("enter the phone number: ");
scanf("%s",&phone);
*ptr->phoneNumber = phone;
}
}
else
{
printf("sorry but you have reach max capacity\n");
}
}
the problem is that when I am calling the first fuction after the assignment of values the programm crashes. What is wrong?
Upvotes: 0
Views: 452
Reputation: 1838
you scan a string into a single character. which probably results in memory overrung and thus the behavior of your program is UNDEFINED
scanf("%s",&fname); // here fname is only 1 char long, probably a mistake
Upvotes: 0
Reputation: 1330
You function prototype ID addNew(ID *ptr,int i)
, so you must call it with addNew(ptr,i)
, not using &ptr
because you've already declared ptr
as ID*
.
I hope it helps.
Upvotes: 0