[英]C static pointer for dynamic array
I have a modular C program where each module uses static global variables for shared access of variables between functions of the module but not to other modules. 我有一个模块化的C程序,其中每个模块都使用静态全局变量来共享访问模块功能之间的变量,但不能共享访问其他模块。 Now need a dynamically allocated array that is similarly accessible to all module functions, but I'm not familiar with
malloc
. 现在需要一个动态分配的数组,所有模块函数都可以访问该数组,但是我对
malloc
并不熟悉。 Below is a simplified example of what I'm trying to do. 下面是我正在尝试做的简化示例。 This seems like the right way to do it but I'm trigger shy since I can't find any similar examples (and since the real thing is much more complicated).
这似乎是正确的方法,但是由于找不到相似的示例(而且真实情况要复杂得多),因此我很害羞。 Can I maintain a static pointer like this and use the
malloc
and free
to allocate whatever memory blocks come and go but keeping a good pointer to the current block? 我是否可以像这样维护一个静态指针,并使用
malloc
和free
分配来来去去的任何内存块,但保持指向当前块的良好指针?
static int *dataBlock = NULL;
static int dataSize = 0, dataCursor = 0;
// Init - called externally
int initData(size) {
if (dataBlock || dataSize > 0) {
return -1;
}
dataBlock = malloc(sizeof(*dataBlock) * size);
if (!dataBlock) {
return -1;
}
dataSize = size;
dataCursor = 0;
return 0;
}
// Push - called externally
int pushData(value) {
if (dataCursor >= dataSize) {
return -1;
}
dataBlock[dataCursor] = value;
dataCursor++;
return dataCursor;
}
// Free - called externally
void freeData() {
free(dataBlock);
dataSize = 0;
dataCursor = 0;
dataBlock = NULL;
}
Yes, this will (almost) work. 是的,这将(几乎)起作用。 If you access this structure using multiple threads, it will fail.
如果使用多个线程访问此结构,则它将失败。
There is a defect in pushData. pushData中存在缺陷。 It will place the first element at dataBlock[1].
它将第一个元素放置在dataBlock [1]上。 Assume a size of 3:
假设大小为3:
Call 1 -- dataBlock[1] set 呼叫1-设置了dataBlock [1]
2 -- dataBlock[2] set 2-设置了dataBlock [2]
3 -- dataBlock[3] set -- out of bounds. 3-dataBlock [3]设置-超出范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.