2013-07-23 29 views
2

我在從代碼中的文件中分配數組時遇到問題。該代碼的目的是傳遞給一個函數一個文件名,一個整數將被設置爲文件中的行數和一個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的位置,而不是該值。有沒有人知道我做錯了什麼,以及如何獲得所需的功能?

回答

1
final_list[ii] = temp_item; //setting the array 

您分配一個局部變量的值

複製值,而不是:

strcpy(final_list[ii], temp_item); //setting the array 

另外請注意,您有(使用malloc)爲您希望每個字符串預留空間在陣列中存儲並free在最後,一個簡化的例子:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(void) 
{ 
    char *store_list[100]; 
    char *list[] = { 
     "842B", 
     "832B", 
     "812B", 
     "848B" 
    }; 
    int i; 

    for (i = 0; i < 4; i++) { 
     store_list[i] = malloc(strlen(list[i]) + 1); /* +1 for trailing 0 */ 
     if (store_list[i] == NULL) { /* always check the return of malloc */ 
      perror("malloc"); 
      exit(EXIT_FAILURE); 
     } 
     strcpy(store_list[i], list[i]); 
    } 
    for (i = 0; i < 4; i++) { 
     printf("%s\n", store_list[i]); 
     free(store_list[i]); 
    } 
    return 0; 
} 
+0

大衛,謝謝你的迅速回應。你有沒有想出一個替代方法來解決這個問題,而不需要在函數globel中創建所有的變量? – gabrown86

+1

@David Rf這是一個很好的解釋。不知道這可能發生在C. –

0

我在這段代碼中看到了兩個問題。

1)store_list變量聲明爲char* store_list[100]={0};。該變量可以包含一個指向100 char值的數組的單個指針。然後通過諸如store_list[jj]之類的調用來訪問該變量是可能的,但是不正確的,除非你設計的數據小於sizeof(char*)。以這種方式設計代碼是可能的,但也有許多缺陷,包括您可能無法指望所有系統上的指針大小相同的事實。

2)您必須使用字符串複製功能將字符數據從一個存儲位置複製到另一個位置。您僅通過指定final_list[ii] = temp_item;將指針位置temp_item指定給final_list[ii]。我建議查找strcpy或更安全的版本,以限制要複製的字符數。

相關問題