除了我早先提出的問題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);
我會感激與尋找我究竟做錯了什麼幫助。
謝謝。
標準警告:請[不要轉換](http://stackoverflow.com/q/605845/2173917)'malloc()'和系列的返回值。 – 2015-02-23 14:49:06
請檢查'malloc()' – 2015-02-23 14:51:45