[英]How to retrieve array from void function and pass to other functions in Main?
[英]Passing array from main function to other functions in C
我有一個在主函數中初始化的動態字符串數組,但我不確定如何正確使用指針並將我的數組發送到函數。 在 function_w 中,我想處理數組,然后將其發送回主函數,稍后再用於其他函數。 這是我的代碼:
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;
}
每次我使用 function_w 時都沒有輸出。 你能幫助我嗎?
char**
,因此指向它的指針是char***
。function_w
的調用者需要信息strcount
,所以你應該返回它。FILE*
的指針,因為您不會修改它。應用這些,你的程序應該是這樣的:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.