閱讀「C編程語言手冊」中關於結構的章節後,我嘗試了下面的代碼。目標是讓一個指針數組初始化爲其所有點的某個特定值。獲取函數返回參數的地址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功能並返回一個有效點的對象?
由於提前,
請注意,即使這是合法的,它也會導致UB,因爲從函數返回的值在當前語句後不再存在 – 2014-11-01 01:01:43