c - C 中获取函数返回参数的地址

标签 c pointers

读完《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/

相关文章:

c - 函数 printf 在 C 中如何工作?

arrays - 用于调用 C 函数的 Fortran 接口(interface),该函数返回指向数组的指针

c - C 中的参数值不可变?

c++ - 空引用 - C++ 标准中的位置

c++ - 修改指针属性

python - 2x2矩阵中元素的所有组合,行和列的总和等于指定的值

c - C中的段错误,似乎无法找到原因

c - 在c中分割字符串而不改变原始字符串

c - 包含内部指针的 union 的内存分配如何

c - C中的指针(指针的值)?