读完《C 编程语言》一书中有关结构的章节后,我尝试了以下代码。目标是使用其所有点的某个特定值初始化一个指针数组。
#include <stdio.h>
#define MAXPOINTS 1000
struct point {
int x;
int y;
};
struct point makepoint(int x, int y);
int main(int argc, const char *argv[])
{
int i;
int number1 = 5, number2 = 10;
struct point *points[1000];
for (i=0; i< MAXPOINTS; i++) {
points[i] = &(makepoint(number1, number2));
}
}
struct point makepoint(int x, int y) {
struct point my_point;
my_point.x = x;
my_point.y = y;
return my_point;
}
运行上述代码后产生的错误如下:
test_something.c:18:22: error: cannot take the address of an rvalue of type 'struct point'
既然 makepoint 函数确实返回了一个有效的点对象,为什么会发生这种情况?
提前致谢,
最佳答案
您返回一个点的临时副本并获取他的地址不是一个好主意。 试试这个:
struct point* makepoint(int x, int y);
int main(int argc, const char *argv[]) {
int i;
int number1 = 5, number2 = 10;
struct point* points[MAXPOINTS];
for (i=0; i< MAXPOINTS; i++)
points[i] = makepoint(number1, number2);
for (i=0; i< MAXPOINTS; i++)
free(points[i]);
return 0;
}
struct point* makepoint(int x, int y) {
struct point* my_point = malloc(sizeof(struct point));
my_point->x = x;
my_point->y = y;
return my_point;
}
无论如何,在你的代码中:
struct point *points[10];
for (i=0; i< MAXPOINTS; i++) {
points[i] = &(makepoint(number1, number2));
}
...您有一个包含 10 个指针的数组,并且您正在尝试分配 1000 个指针 (MAXPOINTS)。
关于c - C 中获取函数返回参数的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203898/