我試圖從file1.c中的child_prog()
到main()
返回一個數組。我試着給出下面的僞代碼。malloc'ed數組到stack'ed數組的分配
#include<stdio.h>
#include<stdlib.h>
int* child_prog(int some_input);
void main(void){
int C[10];
int some_input;
C = child_prog(some_input);
}
int* child_prog(int some_input){
static int out[10];
...
.../*some wizardry*/
return out;
}
現在,編譯器產生一個錯誤說,它不能分配給C
(這是一個int []型)從child_prog返回的值(這是一個int *類型)。雖然,當我製作C
時,程序工作正常,int*
和malloc
是10 ints
的內存。我不明白爲什麼編譯器不能分配到C
(一個數組定義爲C[10]
,因此一個指針)從child_prog
(一個數組定義爲static int out[10]
,因此也是一個指針)返回的值。
好的,理解點數爲1即int *!= int []。但是,如果我將C定義爲int * C而不是int C [],並且malloc是已知的內存量,並且child_prog返回C指向靜態int數組的指針,我應該不能繞過需要做memcpy? – Abhinav
如果你不是分配給一個數組,而是分配給一個指針,你不需要'memcpy'。 – MByD
感謝您殺死我的很多龍......相當快 – Abhinav