I have a dynamic array of strings initialized in the main function, but I'm not sure how to properly use pointers and send my array to function. In the function_w I want to work with the array and then send it back to main function, and later to use in other functions. This is my code:
char function_w(char **array,FILE **fr)
{
int i = 0, strcount = 0;
int buf_length = 50;
char buf [buf_length],p = NULL;
fseek(*fr, 0, SEEK_SET);
while (fgets(buf, buf_length, *fr) != NULL)
{
array = (char **)realloc(array, (strcount + 1) * sizeof(char *));
array[strcount++] = strdup(buf);
}
return p;
}
int main(void)
{
char **array = NULL;
FILE*fr = NULL; //file is opened in other function, before calling w
...
if (fr != NULL) **array = function_w(array,&fr);
else printf("Error");
return 0;
}
Every time I use function_w there's no output. Can you help me?
char**
in this case, so a pointer to that is char***
.function_w
will want the information strcount
, so you should return that. FILE*
because you don't modify that.Applying these, your program should be like this:
int function_w(char ***array,FILE *fr)
{
int i = 0, strcount = 0;
int buf_length = 50;
char buf [buf_length],p = NULL;
fseek(fr, 0, SEEK_SET);
while (fgets(buf, buf_length, fr) != NULL)
{
*array = realloc(*array, (strcount + 1) * sizeof(char *));
(*array)[strcount++] = strdup(buf);
}
return strcount;
}
int main(void)
{
char **array = NULL;
FILE*fr = NULL; //file is opened in other function, before calling w
int strcount;
...
if (fr != NULL) strcount = function_w(&array,fr);
else printf("Error");
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.