c - 从文件中分配一个 char* 数组

标签 c arrays file function assign

我在从代码中的文件分配数组时遇到问题。该代码的目的是向函数传递一个文件名,一个整数,该整数将被设置为文件中的行数和一个 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 的位置,而不是值。有谁知道我做错了什么以及如何获得所需的功能?

最佳答案

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;
}

关于c - 从文件中分配一个 char* 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17813336/

相关文章:

python - 在Python中读取文件并将列放入数组中

c - 当输入不匹配格式时,scanf_s 返回什么?

arrays - 如何将自定义属性添加到PowerShell数组?

c - 如何在 C 中返回一个 char**

javascript - array.push() 但数组中没有结果?

java - 一次读入文本文件 1 行并将单词拆分为 Array Java

linux - 无法删除攻击者留下的文件$$$222.php

c - 读取/proc/pid/mem 文件不返回任何内容

c - 如何找到我当前的编译器标准,例如是否是 C90 等

c - nedmalloc:mem>=fm 从何而来?