我有一个简单的结构。
struct grades
{
int lowest;
int highest;
};
然后我将创建一个函数,该函数返回一个初始化结构的指针。
struct *grades setGrades(int low, int high)
{
struct *ptr = malloc(sizeof(struct grades));
ptr->lowest = low;
ptr->highest = high;
return ptr;
}
现在我应该创建一个定义为 struct **grades random(int size);
的函数
我应该为指向 grade
结构的指针数组分配空间,其中元素的数量等于 size
。创建指针数组时,我想将数组中的每个指针设置为新创建的数据结构,低变量等于 10,高变量等于 100,然后返回指针。
此时我真的迷路了,因为我在网上查找了指向结构的双指针,但没有找到任何可以帮助我理清理解的例子。我想知道是否有人可以向我解释指向结构的双指针是如何工作的,这会让我在正确的方向上有一个良好的开端。
最佳答案
您所说的“双指针”只是指向指针的指针。也就是说,struct grade example
是一个包含您定义的 lowest
和 highest
的变量。指向那个的指针,struct grade *example
是一个变量,存储相同结构的内存地址。指向指针的指针,struct grade **example
,是一个变量,它存储一个变量的内存地址,这个变量存储你的结构体的内存地址。可以找到更详细的解释here .无论如何,要回答您的具体问题,一个函数是:
struct grades** random(int size) {
struct grades** result = malloc(sizeof(struct grades*) * size); //here you are
//allocating enough space for an
//array of pointers
int i;
for(i = 0; i < size; i++) {
result[i] = setGrades(10, 100); //here you are setting each pointer to one
//grade through the function you've already
//defined
}
return result;
}
关于c - 指向 C 中结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26163333/