c - 从函数返回多个指针

标签 c pointers

我试图返回 4 个指针,这些指针存储在 C 中函数的另一个指针中,但出现段错误。 有谁知道该怎么做吗?

这就是我尝试这样做的方式:

//declaration of 5 pointers (int * ptr0, float * ptr1, ..., int * ptr4)

int * function()
{
    int * ptr;
    ptr = malloc(sizeof(int)*4);

    float * ptr1;
    ptr1 = malloc(sizeof(float)*4);

    float * ptr2;
    ptr2 = malloc(sizeof(float)*4);

    float * ptr3;
    ptr3 = malloc(sizeof(float)*4);

    int * ptr4;
    ptr4 = malloc(sizeof(int)*4);

    retunr ptr;
}

ptr0 = function();
ptr1 = ptr0[0];
ptr2 = ptr0[1];
//and so on...

好吧,我改变了我的程序,但现在我不能再写入指针了。 我知道这是一个非常“愚蠢”的问题,但我真的不知道。 有人可以帮忙吗?

最佳答案

函数只能返回单个值。一个简单的解决方案是返回一个包含所需指针的结构。

struct pointers {
    float* ptr1;
    float* ptr2;
    float* ptr3;
    // or perhaps an array instead:
    // float* f_ptrs[3];
    int*   ptr4;
}

struct pointers function() {
    struct pointers p;
    // initialize the members here
    return p;
}

关于c - 从函数返回多个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37947640/

相关文章:

c++ - 通过引用传递数组?

c++ - 在 C++ 对象中 : Should I be casting pointers with the parent class or should I be casting with the actual class itself

pointers - 通过传递指针更改 slice

c++ - C++ 中重载的指针问题?

C程序没有正确添加 float

c - 为什么 `pLQ->tail`是空指针?

c - 如何从系统调用中提取错误?

c - 标准定义了变量的顺序吗?

c - 如何使我的代码符合 MISRA 2012 规则 10.4

c - 查找c头文件中的所有宏定义