我在從代碼中的文件中分配數組時遇到問題。該代碼的目的是傳遞給一個函數一個文件名,一個整數將被設置爲文件中的行數和一個char *數組,每行一個,在函數內文件將被打開,每個行傳入數組。從文件中分配char *數組
,我想開是Storelist.txt和包含的文件:
842B
832B
812B
848B
代碼的主要功能是:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h> /* strtol */
void pass_list(int *final_legnth_list, char* filename, char* final_list[]);
main(int argc, char* argv[])
{
int store_n=0;
char* store_param= "storelist.csv";
char* store_list[100]={0};
pass_list(&store_n,store_param, store_list);
printf("STATUS: size of array [%i]\n",store_n);
int jj=0;
for(jj=0;jj<store_n;jj++){
printf("Number: %i is store: [%s]\n",jj, store_list[jj]);
}
return 0;
}
最後的功能是:
void pass_list(int *final_legnth_list, char* filename, char* final_list[]){
FILE *temp_file; //opening the file
temp_file = fopen (filename, "rt");
int ii=0;
if (temp_file!=NULL){
char temp_line[30];
char temp_item[30];
while(fgets(temp_line, 30, temp_file) != NULL){ //looping over the lines
sscanf(temp_line,"%s",temp_item); //getting the value without the end line
printf("STATUS:output = [%s]\n",temp_item);
final_list[ii] = temp_item; //setting the array
ii++;
}
(*final_legnth_list) = ii;
}
}
最終輸出顯示:
STATUS:output = [842B]
STATUS:output = [832B]
STATUS:output = [812B]
STATUS:output = [848B]
STATUS: size of array [4]
Number: 0 is store: [848B]
Number: 1 is store: [848B]
Number: 2 is store: [848B]
Number: 3 is store: [848B]
因此,它正在從文件讀取正確的值,但不知何故它總是完成分配給文件的最終值。
我認爲這可能是由於數組存儲temp_item的位置,而不是該值。有沒有人知道我做錯了什麼,以及如何獲得所需的功能?
大衛,謝謝你的迅速回應。你有沒有想出一個替代方法來解決這個問題,而不需要在函數globel中創建所有的變量? – gabrown86
@David Rf這是一個很好的解釋。不知道這可能發生在C. –