in this code I want to get a number of friends and then get the names i want the strings will be allocated dynamically with the lengh of the user input i have used with 2 functions:
void getNum(char** names, int* num)
{
//somecode
names = (char*)malloc(*num * sizeof(char));
//check
}
void getNames(char** names, int* num)
{
int i = 0;
int len = 0;
char name[LEN] = { 0 };
getchar(); //buffer cleaning
for (i = 0; i < *num; i++)
{
printf("enter #%d friend name: ", i+1);
myFgets(name, LEN); //getting name and cleaning "\n" at end
len = strlen(name)+1; // getting the size of string include "/0"
*(names + i) = (char*)malloc(len * sizeof(char));
if (*(names[i]) == NULL)
{
printf("Error allocating memory!\n"); //print an error message
return 1; //return with failure
}
strncpy(*names, name, len);
}
}
the second dynamic allocation doens't work for me, overflow eror: "Access violation writing location". If the first allocation will be in the second function it will work fine. Can u explain that? and what I need to do for it will work in that way? thank you in advance...
getnamesandgetNum.names = (char*)malloc(*num * sizeof(char));should benames = (char*)malloc(*num * sizeof(char*));getNumseems pretty pointless, as it is called by nothing in the posted code.getNum(names, &num); getNames(names, &num);and initializedchar** names = NULL;i want it will stay like that