[英]How do I fill an array with pointers to structs
我必须用指向结构的指针填充数组。 结构为:
typedef struct {
char* name;
double weiten[3];
} springer;
现在,我想填充一个数组springer * spr []。 我有一个名为namen的字符串数组,而n是最后要包含在数组中的元素数。
填充数组的函数:
void fuellen(springer *spr[], const char* namen[], int n){
spr=calloc(n,sizeof(springer));
for(int i=0;i<n;i++){
(*spr[i]).name=calloc(30,sizeof(char));
strcpy((*spr[i]).name, namen[i]);
spr[i]->weiten[0]=zufallsWeite();
spr[i]->weiten[1]=zufallsWeite();
spr[i]->weiten[2]=zufallsWeite();
}
}
因此,数组所指向的结构应使用在我的char数组中具有名称作为名称的结构填充。 数组也是结构的一部分,应填充3个随机生成的6到9之间的数字(zufallsWeite()会为您提供这些数字。
现在在主要功能中,我想使用该功能:
const int N = 5;
const char *names[] = {"Tom Mueller","Timo Meier","Ulf Sommer","Tobi
Winter","Uwe Schmidt"};
springer *spr[N];
fuellen(spr, names, N);
构建工作,但随后程序关闭,我收到一条错误消息。 有人可以告诉我我做错了吗? 我已经寻找了一段时间,但没有发现任何东西。
您有(我添加的评论):
void fuellen(springer *spr[], const char* namen[], int n){
// At this point, spr is a pointer to the first element in
// the array that was passed into the funtion.
spr=calloc(n,sizeof(springer));
// Now spr, a local pointer value, points to zeroed memory in the heap.
// The following loop copies strings from namen[] to spr[].
for(int i=0;i<n;i++){
//(*spr[i]).name=calloc(30,sizeof(char));
//strcpy((*spr[i]).name, namen[i]);
strdup(namen[i];)
spr[i]->weiten[0]=zufallsWeite();
spr[i]->weiten[1]=zufallsWeite();
spr[i]->weiten[2]=zufallsWeite();
}
// Unfortunately, all that work, including the heap
// allocation is lost when this function returns.
}
只是不要用calloc
覆盖spr
。
void fuellen(springer *spr[], const char* namen[], int n){
// spr[] was allocated by the caller!
// Allocate each element of the array and initialize the struct.
for(int i=0;i<n;i++){
spr[i] = malloc(sizeof(springer));
spr[i]->name = strdup(namen[i]);
spr[i]->weiten[0]=zufallsWeite();
spr[i]->weiten[1]=zufallsWeite();
spr[i]->weiten[2]=zufallsWeite();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.