【发布时间】:2010-10-12 10:07:06
【问题描述】:
我正在尝试读取格式为“ADAM”、“MARK”、“JESSIE”的随机名称的文件.....
我有一些限制,文件应该在函数中读取,但应该可以从没有全局变量的主函数中访问。 文件大小和文件中的名称数量未知。 这就是我到目前为止所做的。我对动态二维数组有一些困难,因为我没有经常使用它们。
/* Function to read from the file */
int read_names(FILE *input, char ***names, int *name_count)
{
int f1,size,count,i,j=0;
char **name_array,*text,pos=0;
/* get the file size */
f1=open("names.txt",O_RDONLY);
size=lseek(f1,0,SEEK_END);
close(f1);
/* Reading all the characters of the file into memory */
//Since file size is known we can use block transfer
text=(char *) malloc(size * sizeof(char) );
fscanf(input,"%s",text);
/* Finding the no of names in the file */
for(i=0;i<size;i++)
{
if(text[i]==',')
count++;
}
printf("No. of names determined\n");
/* Assigning the Name count to the pointer */
name_count=(int*)malloc(sizeof(int));
*name_count=count;
name_array=(char **) malloc(count * sizeof(char *));
for(i=0;i<count;i++)
{
name_array[i]=(char*) malloc(10 *sizeof(char ));
}
for(i=0;i<size;i++)
{
if(text[i]!='"')
if(text[i]==',')
{
**name_array[pos][j]='\0'; //error here
pos++;
j=0;
}
else
name_array[pos][j++]=text[i];
}
printf("Names Counted\n");
printf("Total no of names: %d\n",*name_count);
names=(char ***) malloc(sizeof(char **);
names=&name_array;
return 1;
}
/* Main Function */
int main(int argc, char *argv[])
{
FILE *fp;
char ***names;
int *name_count;
int status;
// Opening the file
fp = fopen("names.txt","r");
// Now read from file
status = read_names(fp,names,name_count);
printf("From Main\n");
fclose(fp);
system("PAUSE");
return 0;
}
当我尝试分配空字符时,我使用 WxDev 并收到错误“'unary *' 的类型参数无效。
关于如何做到这一点的任何指示?
【问题讨论】:
-
您可能想尝试格式化您的代码,因为其他人很难以现在的形式阅读。
-
您打开“names.txt”两次的事实应该向您表明存在某种问题。
-
函数read_names中char*** name有什么用?
-
@Paul:我会改进 cmets...@sje397:嗯... din 真的考虑一下,因为我没有收到警告或错误,而且我以只读方式打开它们认为我没有收到任何错误。 @Manoj R:我现在编辑了代码以指示使用三重指针。我以为我可以通过这种方式在主函数中访问这个二维数组。
标签: c pointers dynamic multidimensional-array 2d