【问题标题】:Need help scanning the contents of a file into an array of pointers需要帮助将文件的内容扫描到指针数组中
【发布时间】:2011-08-26 05:33:17
【问题描述】:

我需要读入一个文件,文件的每一行都有一个字符串(最多 50 个字符长),我需要将每一行存储到一个指针数组中。因此,如果文件读取:

1234
abcd
5667
...

那么数组(称为函数)将是 *functions[0] = 1234, *functions[1]= abcd 等等...

我现在已经尝试了一些东西,但我似乎无法让它发挥作用。这是我的代码的开始,或者至少是与我的困惑有关的部分:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 201            /* 200 is th emax number of lines in the file*/
#define MAX_FUNCTION_LENGTH 51    /* each line is at ax 50 characters long

main() {
    char func[MAX_FUNCTION_LENGTH]
    char * functions[MAX_SIZE]      /* this is my ragged array*/    
    FILE * inf;
    inf =fopen("list.txt", "r");

我尝试了一些方法,但无法让 *functions 正确存储值。有人可以帮我吗? :)

【问题讨论】:

  • 您是否尝试使用 malloc() 进行初始化?
  • yeha 我试过这样做,问题是我通常只是根据我使用的方法用最后一行或第一行填充每个指针

标签: c arrays pointers input


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 201

int main( int argc, char **argv ) {
    FILE *fp = fopen ( "D:\\personal\\input.txt","r");
    if ( !fp )
        exit ( -1 );
    char line [50];
    char *functions[MAX_SIZE];
    int index = 0;
    while (!feof(fp)) {
        fgets (line , 50 , fp);
        functions[index++] = strdup (line);
    }
    fclose ( fp );
    for ( int i = 0; i < index; i++) {
        printf ( "[%d] -> [%s]\n", i, functions[i]);
    }
    for ( int i = 0; i < index; i++) {
           free ( functions[i]);
}
}

【讨论】:

  • strdup 是非标准的(尽管实现起来很简单),并且在不再需要数据时还需要freeing(OP 似乎希望避免这种情况。)跨度>
  • 很好,谢谢。正如克里斯所说,可能需要一些帮助来释放,我该怎么做?
猜你喜欢
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-02
  • 2011-07-20
  • 2020-06-30
  • 1970-01-01
相关资源
最近更新 更多