【问题标题】:assign each value of a column into a dynamically created global array将列的每个值分配到动态创建的全局数组中
【发布时间】:2014-03-03 22:06:31
【问题描述】:

我正在尝试将文本文件中列的每个值存储到动态分配的数组中,该数组需要全局声明以便在程序中进一步使用。

输入文本文件包含以下内容: 34932\t13854\t13854\t2012-01-07\r 172098\t49418\t53269\t2012-01-07\r

我写了以下代码:

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

    int main()
    {
        FILE *int_file1;
        int BUF = 1024;

        char first_col[BUF],sec_col[BUF],third_col[BUF],fourth_col[BUF];

        int index=0,i=0;

        char *array1=malloc(10*sizeof(char));

        int_file1=fopen("test.txt","r");

        if(int_file1 == NULL)
        {
            perror("Error while opening the file.\n");
        }
        else
        {
            while(fscanf(int_file1,"%[^\t]\t%[^\t]\t%[^\t]\t[^\n]",first_col,sec_col,third_col,fourth_col) == 4)
            {
                             //printf("%s",first_col);
                 array1=realloc(array1,strlen(first_col)+1);
                 array1[index]=first_col;
                 index++;
            }
        }

        fclose(int_file1);  

        printf("%s",array1[1]);

        return 0;
    }

注释的 printf 行给出了该列的全部值,这证明文件正在被正确读取。

但是在编译这个程序时,我得到了编译器警告和最后的分段错误。

请指出我哪里弄错了。

【问题讨论】:

  • 如果您发布编译器警告会有所帮助,另外,它在哪一行出现段错误?
  • 编译错误是:
  • program.c:在函数'main'中:program.c:113:警告:赋值从没有强制转换的指针中生成整数program.c:120:警告:格式'%s'需要类型' char *',但参数 2 的类型为 'int'
  • 修复这些警告,您的问题可能会得到解决。如果您无法理解它们,请将它们粘贴到谷歌并阅读导致这些警告的原因。
  • 感谢您的建议,但问题是在无法通过谷歌搜索寻求答案后才发布的!希望有人能澄清我的理解..

标签: c arrays dynamic-memory-allocation


【解决方案1】:

如果有帮助,请尝试这样做 而不是这个

array1=realloc(array1,strlen(first_col)+1);

尝试这样做

temp = realloc(array1,strlen(first_col)+1);

array1=temp;

array1[index]=first_col;//You can't do this, You can do this if array1 is double pointer.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 2013-12-18
    相关资源
    最近更新 更多