如何使用指向结构

时间:2018-05-24 07:57:07

标签: c arrays pointers struct

我必须使用指向结构的指针填充数组。 结构是:

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()给你那些。

现在在main函数中我想使用函数:

const int N = 5;
const char *names[] = {"Tom Mueller","Timo Meier","Ulf Sommer","Tobi 
Winter","Uwe Schmidt"};

springer *spr[N];
fuellen(spr, names, N);

构建工作,但程序关闭,我收到一条错误消息。 有人可以告诉我我做错了什么吗?我一直在寻找,但我没有找到任何东西。

1 个答案:

答案 0 :(得分:0)

你有(我添加评论):

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.
}

请勿通过调用spr覆盖calloc

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();
    }
}