从一个文件读取数据到二维数组中,下面的程序错在哪?
程序代码:
#include<stdio.h> int main(int argc,char *argv[]){ if(argc!=2){ fprintf(stderr,"usage:%s filename\n",argv[0]); exit(1); } FILE *f1; char a1[3][3]; f1=fopen(argv[1],"r"); if(f1==NULL){ fprintf(stderr,"%s: file no found\n",argv[1]); exit(1); } char *str1=(char *)malloc(100); int i=0,ret; while(fgets(str1,100,f1)!=NULL){ if((ret=sscanf(str1,"%s %s %s",&a1[i][0],&a1[i][1],&a1[i][2]))<3){ fprintf(stderr,"sscanf() call error,ret=%d\n",ret); exit(1); } i++; } for(i=0;i<3;i++){ fprintf(stdout,"%s %s %s\n",a1[i][0],a1[i][1],a1[i][2]); } exit(0); }[view@localhost c]$cat 1.txt
1 a b
2 c d
3 e f
[view@localhost c]$cc -o test1 test1.c
[view@localhost c]$./test1 1.txt
Segmentation fault (core dumped)
(gdb) where
#0 0x005dfc7b in strlen () from /lib/tls/libc.so.6
#1 0x005b4155 in vfprintf () from /lib/tls/libc.so.6
#2 0x005b940f in fprintf () from /lib/tls/libc.so.6
#3 0x08048671 in main ()
(gdb)
[ 本帖最后由 khaz 于 2011-4-23 15:11 编辑 ]