在此代码中替换malloc / free

时间:2012-06-07 03:07:02

标签: c

以下代码存储指针tmpbuffer。我如何将tmpbuffer本身而非指针存储在fwBuffer这样的数组中,而不是malloc / free

short int *fwBuffer[1000000];

size =  sizeof(short int)*length*inchannels;
short int *tmpbuffer = (short int*)malloc(size);

int count = 0;
for (count = 0; count < length*inchannels; count++)
{
    tmpbuffer[count] = (short int) (inbuffer[count]);
}

fwBuffer[saveBufferCount] = tmpbuffer;

2 个答案:

答案 0 :(得分:1)

short int *fwBuffer[1000000];

1000000类型的short int指针数组 指针本身没有用,除非它指向一些有效的内存,属于一个有效的对象,在这种情况下属于short int类型的对象。

代码为short int分配足够的内存,然后将该指针放在数组中,从而使该数组有用。这是正确的方法,因为你需要1000000项,如果你在堆栈上分配它们,你可能会耗尽堆栈空间。

答案 1 :(得分:0)

你想做这样的事吗?这会将所有存储的缓冲区聚合到一个缓冲区中。请注意,我有一个单独的缓冲区来存储索引;要么你可能不需要这个,要么你理论上可以将它打包到fwBuffer数组中的一个位置。

// Max number of data chunks
const unsigned maxBuffers = 1024;
// All the data stored here.
short int fwBuffer[1000000];
// how many data chunks we have
unsigned saveBufferCount = 0;
// Index to find each data chunk
// bufferIndex[saveBufferCount] points to where the next buffer will be placed (i.e. _after_ all the stored data).
short int* bufferIndex[maxBuffers] = {fwBuffer};

void storeBuffer(unsigned length, unsigned inchannels, short int* inbuffer)
{    
        short int *bufferIterator = bufferIndex[saveBufferCount];
        // Could do a memcpy here.
        int count = 0;
        for (count = 0; count < length*inchannels; count++)
        {
            *bufferIterator++ = inbuffer[count];
        }       
        ++saveBufferCount;
        bufferIndex[saveBufferCount] = bufferIterator;
}