[英]fscanf with 2d array within dynamic struct using only pointers
因此,本次练习是我第一次使用C ++来自指针。 我的教授希望我们在不使用索引的情况下进行此练习以更好地掌握指针。 我正在尝试从文件中读取嵌入动态分配的结构中的二维数组。 我希望我已经很好地表达了我的问题,并提供了适当的信息。 非常感谢你。
我的结构
typedef struct //struct that holds ASCII art
{
char artistName[80]; //name of artist
char asciiArt[20][80]; //actual ascii art line by line
int rating; //rating of art
}TextArt;
结构声明和分配数组
TextArt **artPtr;
artPtr = malloc(1000 * sizeof(TextArt) + 1);
代码行给我带来了问题。 我从文件读取到现在为止,我不确定这是否有效,我在第一个字符中寻找#。 不使用索引的语法对我来说非常令人困惑,因此这是我需要最大帮助的地方。 它是指向struct(* asciiArt + i)数组的指针,然后指向struct-> 2d c字符串数组asciiArt [] []。
while(*tempLine != '#') //while there is no # in position [0] -- read into temp string
{
printf("while templine\n");
fgets((*asciiArt+i)->asciiArt, 100, pFile);
}
如果您需要更多信息,请使用上述代码的完整功能,否则请忽略此代码块。
void readFromFile(TextArt **asciiArt, int size, char *fileName)
{
int index = 0; //index for array of struct
int i = 0;
int j = 0;
char tempLine[500]; //temp placeholder
FILE *pFile;
pFile = fopen (fileName ,"r");
if (pFile == NULL)
printf("Error opening file");
else
{printf("file opened.");
for(i = 0; pFile != NULL; i++) //*(*(data + i) + j)
{ j=0;
fgets((*asciiArt+i)->artistName, 100, pFile); //get artist name from first line
printf("got artist name");
while(*tempLine != '#')
{printf("while templine\n");
fgets((*asciiArt+i)->asciiArt, 100, pFile); //while there is no # -- read into temp string
}
strcpy(tempLine, ""); //clear temp string
printf("for loop done");
}
return;
}
}
这是个错误:
TextArt **artPtr;
artPtr = malloc(1000 * sizeof(TextArt) + 1);
sizeof(TextArt)
与sizeof(TextArt *)
无关。 artPtr
指向一个指针数组 ,而不是一个TextArt对象数组。 您刚刚分配(或尝试分配)的那1000个指针中的每一个当前均指向无处,在使用它们之前,您必须将每个指针指向某处。
更新 :OP阐明了分配1000个TextArt
数组的意图:
TextArt *artPtr;
artPtr = malloc(1000 * sizeof(TextArt));
我不确定+ 1
是什么意思。
如果readFromFile
函数需要调整数组大小,则可以像这样传递它:
void readFromFile( &artPtr, ......
在函数内部,您可以像这样访问它:
fgets((*asciiArt)[i].artistName, 100, pFile);
其实我会写
TextArt *artPtr = *asciiArt;
fgets( artPtr[i].artistName, 100, pFile );
因为它更容易阅读,而不是到处都有括号。
如果该函数不需要重新分配,则只需使用TextArt *artPtr;
。
大概
TextArt *artPtr;
artPtr = malloc(1000 * sizeof(TextArt));
...
void readFromFile(TextArt *asciiArt, int size, char *fileName){
int index, i, ch; //index for array of struct
char tempLine[500];
FILE *pFile;
pFile = fopen (fileName ,"r");
if (pFile == NULL)
printf("Error opening file");
else{
printf("file opened.");
for(index = 0; index < size; ++index){
TextArt *pta = asciiArt + index;
fgets(pta->artistName, sizeof(pta->artistName), pFile);
printf("got artist name");
for(i=0;i<20;++i){//20 : sizeof(pta->asciiArt)/sizeof(pta->asciiArt[0])
if(EOF==(ch=fgetc(pFile))){
index = size;//outer loop break
break;
} else if(ch == '#'){
//ungetc(ch, pFile);
fgets(tempLine, sizeof(tempLine), pFile);
break;
} else {
ungetc(ch, pFile);
fgets(pta->asciiArt + i, sizeof(pta->asciiArt[0]), pFile);
}
}
}
fclose(pFile);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.