除了我早先提出的问题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