简体   繁体   English

无法在C中返回多维数组

[英]Fail to return a multidimensional array in C

I'm trying to write a function in C, which returns the pointer to an array. 我试图用C编写一个函数,该函数将指针返回数组。 Each element of this array is a pointer to the initialized structure, and in each structure there's also a pointer to an array. 该数组的每个元素都是指向初始化结构的指针,并且在每个结构中也都有指向数组的指针。

struct queueRecord;
typedef struct queueRecord* queue;

queue createQueue(int maxSize){
    queue newQueue = malloc(sizeof(struct queueRecord));
    newQueue->array = malloc(sizeof(int)*maxSize);
    newQueue->capacity=maxSize;
    newQueue->front=0;
    newQueue->rear=0;
    return newQueue;
}

This just works fine as well as in the following function: 这和下面的函数一样正常工作:

queue* initQArr(int maxSize){
    queue arr[10];
    for (int i=0; i<10; i++) {
        arr[i]=createQueue(maxSize);
    }
    return arr;
}

when I pass the parameter 10 in it and set a breakpoint at return, everything seems good (excuse me I can't post images, the debug information is like following): 当我在其中传递参数10并在返回时设置断点时,一切似乎都很好 (对不起,我无法发布图片,调试信息如下):

arr(queue[10])
 [0]=(queue)0x100105480
   capacity=(int)10
   size=(int)0
   front=(int)0
   rear=(int)0
   array=(int*)0x1001054a0
 [1]=(queue)0x1001054d0
 ...
 ...
 [9]=(queue)0x100105760

However!When I invoke this function and return to a new array, I got an array with only 5 elements: 但是,当我调用此函数并返回到新数组时,我得到的数组只有5个元素:

queue *digitsQArr = initQArr(length);
int digit = 0;

(debug information as following): (调试信息如下):

digitQArr = (queue*)0x7fff5fbff6d0
    *digitsArr=(queue)0x100105480
        capacity=(int)10
        size=(int)0
        front=(int)0
        rear=(int)0
        array=(int*)0x1001054a0
    [1]=(queue)0x1001054d0
    ...
    ...
    [4]=(queue)0x1001055d0

In initQArr , you return the address of a local variable, arr : initQArr ,返回本地变量arr的地址:

queue* initQArr(int maxSize){
    queue arr[10];
    for (int i=0; i<10; i++) {
        arr[i]=createQueue(maxSize);
    }
    return arr;
}

The returned pointer will point to the local array arr , which is no longer valid once the function returns. 返回的指针将指向本地数组arr ,一旦函数返回,该数组将不再有效。 You could follow the example of createQueue and allocate memory on the heap: 您可以按照createQueue的示例在createQueue分配内存:

queue* initQArr(int maxSize){
    queue *arr = malloc(10 * sizeof(*arr));
    for (int i=0; i<10; i++) {
        arr[i]=createQueue(maxSize);
    }

    return arr;
}

After returning, the pointer arr is still valid, because it points to memory on the heap. 返回后,指针arr仍然有效,因为它指向堆上的内存。 You should free such memory after using it, like the queue pointers allocated in createQueue . 使用后应free此类内存,就像createQueue分配的队列指针createQueue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM