2015-02-23 75 views
1

除了我早先提出的問題Dynamically allocating an array in a function in C ,這個問題已得到解答並且工作正常,如果我的結構字段之一是指針本身,它似乎不起作用。動態分配函數中的內存函數C

這裏是我想現在要做的:

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

typedef struct myData { 
    unsigned char* dataBuffer; 
    int lengthInBytes; 
}myData; 


// suppose this is dynamic. it return a value according to some parameter; 
int howManyDataBuffers() { 
    // for this demo assume 5. 
    return 5; 
} 

// this just fills data for testing (the buffer is set with its length as content. exp:3,3,3 or 5,5,5,5,5) 
int fillData(int length, myData* buffer) { 
    buffer->dataBuffer = (unsigned char*)malloc(length); 
    memset(buffer->dataBuffer,length,length); 
    buffer->lengthInBytes = length; 
    return 1; 
} 

int createAnArrayOfData(myData** outArray,int* totalBuffers) { 

    // how many data buffers? 
    int neededDataBuffers = howManyDataBuffers(); 

    // create an array of pointers 
    *outArray =(myData*)malloc(neededDataBuffers * sizeof(myData)); 

    // fill the buffers with some data for testing 
    for (int k=0;k<neededDataBuffers;k++) { 
     fillData(k*10,outArray[k]); 
    } 

    // tell the caller the size of the array 
    *totalBuffers = neededDataBuffers; 

    return 1; 
} 


int main(int argc, const char * argv[]) { 

    printf("Program Started\n"); 

    myData* arrayOfBuffers; 
    int totalBuffers; 
    createAnArrayOfData(&arrayOfBuffers,&totalBuffers); 

    for (int j=0;j<totalBuffers;j++) { 
     printf("buffer #%d has length of %d\n",j,arrayOfBuffers[j].lengthInBytes); 
    } 

    printf("Program Ended\n"); 

    return 0; 
} 

結果是BAD_ACCESS在這一行:

buffer->dataBuffer = (unsigned char*)malloc(length); 

我會感激與尋找我究竟做錯了什麼幫助。

謝謝。

+4

標準警告:請[不要轉換](http://stackoverflow.com/q/605845/2173917)'malloc()'和系列的返回值。 – 2015-02-23 14:49:06

+2

請檢查'malloc()' – 2015-02-23 14:51:45

回答

1

問題是,您正在分配一個結構數組,但使用它(通過outArray[k]),就好像它是一個指針數組一樣。呼叫

fillData(k*10, &(*outArray)[k]); 

代替

的區別是:

outArray[k] == *(outArray+k)這意味着你解引用在位置outArray + k*sizeof(myData*)字節的地址。但是沒有存儲在該位置的有效地址。

&(*outArray)[k]首先取消存儲在位置outArray的地址,這是malloc()(結構數組的起始地址)返回的地址。那麼你可以通過你想要的數組中的第k個結構的地址(如果你願意,你也可以寫(*outArray)+k而不是&(*outArray)[k])。

+0

是否成功謝謝!!!這樣可行。 – 2015-02-23 17:58:50

+0

太好了,歡迎您接受答案 – 2015-02-23 18:15:23