I need to create an array of pointers that will each point to an array of strings. The base, is a size 2 array of strings (the length of the strings is unknown at start). For example an array of 2 strings (first-name and last-name):
char *name[2];
Now I need to create an array of an unknown size (entered by the user) that will point to the type that I just created. My idea was to create it this way:
char **people=name;
And then ask the user how many names he would like to enter and allocate enough space to hold all the names.
people=(char**)malloc(sizeof(char*)*num); //num is the number received by the user.
This is where things got too complicated to me and I can't figure out how to I call each individual name to put a string in it. I built a loop that will receive all the names but I have no idea how to store them properly.
for(i=0;i<num;i++){
printf("Please enter the #%d first and last name:\n",i+1);
//Receives the first name.
scanf("%s",&bufferFirstName);
getchar();
//Receives the last name (can also include spaces).
gets(bufferLastName);
people[i][0]=(char*)malloc(strlen(bufferFirstName)+1);
people[i][1]=(char*)malloc(strlen(bufferLastName)+1);
//^^Needless to say that it won't even compile :(
}
Can anyone please tell me how to properly use this kind of an array of points? Thanks.
people[i][0]=(char*)malloc(strlen(bufferFirstName)+1);is wrong. ifpeopleis achar**thenpeople[0]is achar*andpeople[i][0]is achar. Not a pointer. Also: don't cast malloc()s return value. It is not needed and possibly dangerous, since it can hide errors.peopleshould be a***type instead of**(char ***people)? Also, is there a way of definingpeoplein one line without the use of*name[2]?***you should consider using structs (like in @msider(s) answer)