2014-04-27 73 views
1

int數組我剛學C,和我有一個函數分配數組全局定義的數組問題:不兼容的類型在C

// So I have my multi-dim global array 
uint16_t pulseSets[1][50][2]; 

void foo() 
{ 
    //create another array to work with in here 
    uint16_t pulses[50][2]; 

    // Do some stuff with pulses here 
    // ... 

    // and now assign it to my global array 
    pulseSets[0] = pulses; 

} 

編譯時出現錯誤:

incompatible types when assigning to type ‘uint16_t[50][2]’ from type ‘uint16_t (*)[2]’

pulseSets[0] = pulses; 
      ^

這兩個數組都是相同的類型和大小,所以爲什麼這會打破?

回答

0

在C中,數組內存分配被視爲常量指針,並且在它們創建後不能重新分配。

因此,您的全局聲明uint16_t pulseSets[1][50][2];創建100 intspulseSets[0]點,但pulseSets[0]不能復位在內存其他位置點。

您有2種選擇: 1.複製從pulses[50][2]pulseSets[0]數據在嵌套for循環(其涉及100 INT份) 2.聲明全局pulseSets [1] [50] [2]作爲指針到二維陣列和FOO使用動態存儲器分配()分配給它是這樣:

int **pulseSets[2]; 

void foo() 
{ 
    //create another array to work with in here 
    int **pulses = new int[50][]; 
    for (int i = 0;i<50;i++) 
     pulses[i] = new int[2]; 

    // Do some stuff with pulses here 
    // ... 

    // and now assign it to my global array 

    pulseSets[0] = pulses; 
} 
1

爲什麼它打破,這是因爲「脈衝」被認爲是一個指針(缺失[])。

變通的辦法是使用這樣的結構:

typedef struct { 
    uint16_t Pulses[ 50 ][ 2 ]; 
} Pulse; 

Pulse pulseSets[ 2 ]; 

void foo() 
{ 
    //create another array to work with in here 
    Pulse pulses; 

    // Do some stuff with pulses here 
    // ... 
    memset(pulses, 0, sizeof(pulses)); 

    // and now assign it to my global array 
    pulseSets[ 0 ] = pulses; 
}