gpt4 book ai didi

c - 文件读取问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:48 25 4
gpt4 key购买 nike

如何在 C 中读取使用 FILE*fp 保存的矩阵?

int main()
{
int i,j;
FILE *fp;
int **mat; //matriz de cartas apartir do arquivo
int n; //numero de jogadores
mat=(char**)malloc(3*sizeof(char*));
for(i=0;i<2;i++){
mat[i]=(char*)malloc(3*sizeof(char));
if(!mat){
printf("erro de alocacao\n");
exit(1);
}
}

fp=fopen("arquivo","r"); //this is the file to read
if(fp==NULL){
printf("erro de abertura de ficheiro\n");
exit(1);

}
for(i=0;i<3;i++){
for(j=0;j<3;j++){
fscanf(fp,"%d",&mat[i][j]);
}
printf("%d\n",mat[i][j]); //problem here
}
return 0;
}

这是我要阅读的矩阵:

1 2 9
3 6 7
4 9 5

最佳答案

考虑

for(i=0;i<3;i++){ 
for(j=0;j<3;j++){
fscanf(fp,"%d",&mat[i][j]);
}
printf("%d\n",mat[i][j]); //problem here

存在:

for(i=0;i<3;i++){ 
for(j=0;j<3;j++){
fscanf(fp,"%d",&mat[i][j]);
printf("%d ",mat[i][j]);
}
printf("\n");
}

你发布的内容打印在数组的边界之外

关于c - 文件读取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4238581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com