阅读了“The C programming Language book”中有关结构的章节,我尝试了以下代码。目标是让一个指针数组初始化,并为其所有点指定一些特定值。
#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函数确实会返回一个有效的点对象?
提前致谢,
答案 0 :(得分:2)
您不能获取值的地址,只能获取变量的地址。这是因为价值观不一定需要存在(可寻址)内存中。例如:函数的返回值(通常)通过寄存器传递,您不能获取寄存器的地址(-variable)。
您可以改为使用makepoint
函数来指向struct point
并将其填入:
struct point makepoint(struct point * in, int x, int y){
in->x = x;
in->y = y;
return *in;
}
请注意,返回值并非严格必要,但保留了向后兼容性。
答案 1 :(得分:2)
您正在返回某个点的临时副本并且取他的地址不是个好主意。 试试这个:
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)。