除了我之前的问题Dynamically allocating an array in a function in 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;
}
结果是此行的访问不正确:
buffer->dataBuffer = (unsigned char*)malloc(length);
我会感谢你帮我找出我做错了什么。
谢谢。
最佳答案
问题是,您正在分配一个结构数组,但使用它时(通过outArray[k]
)就好像它是一个指针数组一样。呼叫
fillData( k*10, &(*outArray)[k] );
相反
区别在于:
outArray[k] == *(outArray+k)
这意味着您在outArray + k*sizeof(myData*)
字节处取消引用地址。但那个地方没有有效的地址。&(*outArray)[k]
首先取消引用存储在位置outArray
的地址,该位置是由结构数组的起始地址malloc()
返回的地址。然后在数组中传递第k个结构的地址,这是您想要的(如果您愿意,也可以编写(*outArray)+k
而不是&(*outArray)[k]
)。