2012-05-19 29 views
1

我試圖從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],因此也是一個指針)返回的值。

回答

4
  1. 您不能分配給數組。你需要memcpy吧。
  2. int*!= int[]而第一是一個指針可能指向的int秒的序列的int,第二是序列int小號
  3. 可以使用int *C;和通過的長度數組(如果在編譯時未知)作爲out參數。
  4. static int out[10];不是malloc ed,但是是靜態的。
+0

好的,理解點數爲1即int *!= int []。但是,如果我將C定義爲int * C而不是int C [],並且malloc是已知的內存量,並且child_prog返回C指向靜態int數組的指針,我應該不能繞過需要做memcpy? – Abhinav

+0

如果你不是分配給一個數組,而是分配給一個指針,你不需要'memcpy'。 – MByD

+0

感謝您殺死我的很多龍......相當快 – Abhinav

1

一種解決方案可以申報C作爲:由本雅明 說你不能改變一個數組的地址,因爲它是靜態分配的,這正是你試圖用做

int *C; 

C = child_prog(some_input); 
+0

是的,現在就明白了。感謝您的回覆。 – Abhinav

0
  • 類型的int []int * const這意味着它指向存儲器是一個常數和試圖改變它會給編譯器帶來錯誤。顯然它不等於int *
  • child_prog()中的變量out是靜態分配的,這意味着它不在棧上,而是在全局數據部分的某處。因此,無論您撥打child_prog()多少次,您都將返回相同的內存位置。
  • 因此,要複製陣列,如果要保存從child_prog()返回的數據,請執行memcpy(dest,src,bytes)
+0

感謝您的回覆。 – Abhinav

0
#include<stdio.h> 
#include<stdlib.h> 

#define SUCCESS 0 
#define FAILURE 1 

int child_prog(int some_input, int *output, int output_size); 

void main(void){ 
    int C[10]; 
    int some_input; 
    C = child_prog(some_input, c, 10); 
} 

int child_prog(int some_input, int *output, int output_size) 
{ 
    static int source[10]; 
     ... 
     .../*some wizardry*/ 

    memcpy(output, source, output_size); 


    ... if (erronous Condition) 
      return FAILURE; 
     else 

    return SUCCESS; 
}