C中动态数组的更多问题 [英] More issues with Dynamic Arrays in C
问题描述
你好专家,
在我的帖子里,很多帮助都是给予了帮助,但我仍然无法弄清楚这一点。我有一个如下所述的函数,这个代码的问题可以在for循环中找到,如编译器所示。
hello experts,
In my previos post, alot of help was givin, but still i cant figure this out. I have a function as described here under, and the problem with this code is found in the for loop as indicated by the compiler.
void ReadHighScores(FILE *Scores,int *elements, player_t *playersData)
{
Scores = fopen("Scores.txt","r");
int temp,i;
player_t *playersTemp;
/*getting size of array*/
fscanf(Scores, "%d\n", elements);
playersTemp = (player_t*)realloc(playersData,(*elements) * sizeof(player_t));
playersData = playersTemp;
free(playersTemp);
for(i=0; i<(*elements); i++ )
{
/*Getting Name*/
fscanf(Scores, "%s", playersData[i].Name);
/*Getting Score*/
fscanf(Scores, "%d", &playersData[i].Score);
}
fclose(Scores);
}
我从main调用此函数,如下面的代码所示:
I am calling this function from the main as shown in the code below:
/*Getting the data from file*/
player_t *players;
players = (player_t*)malloc(1 * sizeof(player_t));
ReadHighScores(&Scores,&elements,&players);
for(i=0; i<(*elements); i++ )
{
printf("%s\n",players[i].Name);
printf("%d\n",players[i].Score);
}
正在使用的结构:
The struct that am using:
typedef struct
{
char Name[name_l];
short Score;
}player_t;
我们将非常感谢所有帮助。谢谢专家
All help will be greatly appreciated. Thanks Experts
推荐答案
如果你真的想在运行时更改数组的大小,由于需要重新分配,数组类型不太合适,这是低效的。您最好考虑实现可调整大小的容器,例如链表: http://en.wikipedia。 org / wiki / Linked_list [ ^ ]。
另外,请注意相关结构部分。链表只是最简单的结构之一。
-SA
If you really want to change the size of arrays during runtime, array types are not quite suitable, due to the need for reallocation, which is inefficient. You should better think of implementing of resizeable container, such as linked list: http://en.wikipedia.org/wiki/Linked_list[^].
Also, pay attention for the section "Related structures". Linked list is just one of the simplest structures.
—SA
/ *获取数组大小* /
fscanf(分数,%d \ n,元素); < br $> b $ b
playersTemp =(player_t *)realloc(playersData,(* elements)* sizeof(player_t));
playersData = playersTemp;
免费(playersTemp);
/*getting size of array*/
fscanf(Scores, "%d\n", elements);
playersTemp = (player_t*)realloc(playersData,(*elements) * sizeof(player_t));
playersData = playersTemp;
free(playersTemp);
- 你应该验证
元素
是否有效您的应用程序(例如,假设用户插入负值)。 - 您应该始终检查
realloc
的返回值。 - 你绝不能打电话给
免费(playersTemp)
。代码中的调用是一个错误,因为那时你试图为这样释放的内存赋值。 - You should verify that
elements
is valid for your application (e.g. suppose the user inserts a negative value). - You should always check the return value of
realloc
. - you MUST NOT call
free(playersTemp)
. The call in your code is a blunder, because then you are trying to assign values to such released memory.
这篇关于C中动态数组的更多问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!