在C中的函数中动态分配函数内存

时间:2015-02-23 14:48:17

标签: c

除了我之前的问题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;
}

结果是BAD_ACCESS在这一行:

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

我很感激找到我做错的任何帮助。

感谢。

1 个答案:

答案 0 :(得分: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])。