【发布时间】:2014-04-17 04:22:23
【问题描述】:
所以我是第一次使用 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;
}
}
【问题讨论】:
-
(*asciiArt+i)->asciiArt在上下文中没有任何意义;如果我了解您要正确执行的操作,但我完全不确定,请尝试*(asciiArt+i)。此外,while循环的主体永远不会写入tempLine,因此循环永远不会终止。如果没有看到(a)整个程序,(b)家庭作业提示的整个文本,(c)你自己的描述,我无法给出任何更具体的建议您期望代码执行的操作,以及 (d) 用您自己的话描述发生的事情。 -
仅供参考,这对本网站来说不是一个好问题;与你的同学和/或助教讨论这个问题,你几乎肯定会有更好的运气。
-
加上 Zack 所说的,
malloc使用双指针**artPtr不会使其成为TextArt的数组,但它指向TextArt的指针数组。
标签: c arrays pointers malloc scanf