C 将列的每个值分配到动态创建的全局数组中
我试图将文本文件中列的每个值存储到动态分配的数组中,该数组需要全局声明,以便在程序中进一步使用 输入文本文件包含以下内容: 34932\t13854\t13854\t2012-01-07\r\n 172098\t49418\t53269\t2012-01-07\r\n 我编写了以下代码:C 将列的每个值分配到动态创建的全局数组中,c,arrays,dynamic-memory-allocation,C,Arrays,Dynamic Memory Allocation,我试图将文本文件中列的每个值存储到动态分配的数组中,该数组需要全局声明,以便在程序中进一步使用 输入文本文件包含以下内容: 34932\t13854\t13854\t2012-01-07\r\n 172098\t49418\t53269\t2012-01-07\r\n 我编写了以下代码: #include<stdio.h> #include<stdlib.h> #include<string.h> int main()
#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;
}
#包括
#包括
#包括
int main()
{
文件*int_文件1;
int BUF=1024;
字符第一列[BUF],第二列[BUF],第三列[BUF],第四列[BUF];
int指数=0,i=0;
char*array1=malloc(10*sizeof(char));
int_file1=fopen(“test.txt”、“r”);
if(int_file1==NULL)
{
perror(“打开文件时出错。\n”);
}
其他的
{
而(fscanf(int_file1,“%[^\t]\t%[^\t]\t%[^\t]\t[^\n]”,第一列,第二列,第三列,第四列)==4)
{
//printf(“%s”,第一列);
array1=realloc(array1,strlen(第一列)+1);
数组1[索引]=第一列;
索引++;
}
}
fclose(内部文件1);
printf(“%s”,数组1[1]);
返回0;
}
注释的printf行给出了该列的全部值,这证明文件被正确读取
但在编译这个程序时,我得到了编译器警告和最后的分段错误
请指出我哪里弄错了。如果有帮助,试着这样做 而不是这个
array1=realloc(array1,strlen(first_col)+1);
试着这样做
temp = realloc(array1,strlen(first_col)+1);
array1=temp;
及
如果您发布了编译器警告,这将有所帮助。此外,它在哪一行上分段出错?编译器错误为:program.c:在函数“main”中:program.c:113:警告:赋值从指针生成整数,而不使用强制转换程序。c:120:警告:格式“%s”要求类型为“char*”,但参数2的类型为“int”修复这些警告,您的问题很可能会得到修复。如果你无法理解这些警告,请将它们粘贴到谷歌上,并阅读导致这些警告的原因。谢谢你的建议,但问题是在无法通过谷歌搜索得到答案后才发布的!!希望有人能澄清我的理解。。
array1[index]=first_col;//You can't do this, You can do this if array1 is double pointer.