[英]How do I fill an array with pointers to structs
I have to fill an array with pointers to structs. 我必须用指向结构的指针填充数组。 The struct is:
结构为:
typedef struct {
char* name;
double weiten[3];
} springer;
Now I want to fill an array springer *spr[] . 现在,我想填充一个数组springer * spr []。 I have an array of strings called namen and n is the number of elements that I want to have in the array in the end.
我有一个名为namen的字符串数组,而n是最后要包含在数组中的元素数。
The function to fill the array: 填充数组的函数:
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();
}
}
So the structs that the array points to should be filled with structs that have the names in my char-array as names. 因此,数组所指向的结构应使用在我的char数组中具有名称作为名称的结构填充。 The array that is also part of the structs should be filled with 3 randomly generated numers between 6 and 9 (zufallsWeite() gives you those.
数组也是结构的一部分,应填充3个随机生成的6到9之间的数字(zufallsWeite()会为您提供这些数字。
Now in the main function I want to use the function: 现在在主要功能中,我想使用该功能:
const int N = 5;
const char *names[] = {"Tom Mueller","Timo Meier","Ulf Sommer","Tobi
Winter","Uwe Schmidt"};
springer *spr[N];
fuellen(spr, names, N);
The build works but then the program shuts down and I get an error message. 构建工作,但随后程序关闭,我收到一条错误消息。 Can someone please tell me what I am doing wrong?
有人可以告诉我我做错了吗? I have been looking for a while but I have not found anything.
我已经寻找了一段时间,但没有发现任何东西。
You have (comments added by me): 您有(我添加的评论):
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.
}
Just don't overwrite spr
with a call to calloc
. 只是不要用
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.