我试图返回 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/