静态数组的访问冲突?
我需要使用 win32 线程并行化应用程序。代码的一部分涉及使用线程修改静态数组。
我将数组作为参数传递,如下所示:
struct threadParameter {
float **array;
int row;
}
示例代码如下所示:
// Main
float data[100][100]
for (int i = 0; i < 100; i ++) {
tp = (*threadParameter) new threadParameter;
tp->array = (float **) data;
tp->row = i;
AfxBeginThread... // Begin thread code
}
// Thread Code
UINT myThread(LPVOID param) {
threadParameter *pp = (threadParameter *) param;
for (int j = 0; j < 100; j ++) {
pp->array[pp->row][j] = NEWVALUE;
}
}
但是,在执行项目时,当我尝试通过 **array 指针访问数组时,出现“访问冲突错误”。如果数组数据是,则不会出现此问题 动态的。有什么方法可以解决这个问题(我不允许将数组数据从静态更改为动态)?
I need to parallelise an application using win32 threads. One of the portions of the code involves modifying an static array using threads.
I pass the array as a parameter like this:
struct threadParameter {
float **array;
int row;
}
An example code would be like this:
// Main
float data[100][100]
for (int i = 0; i < 100; i ++) {
tp = (*threadParameter) new threadParameter;
tp->array = (float **) data;
tp->row = i;
AfxBeginThread... // Begin thread code
}
// Thread Code
UINT myThread(LPVOID param) {
threadParameter *pp = (threadParameter *) param;
for (int j = 0; j < 100; j ++) {
pp->array[pp->row][j] = NEWVALUE;
}
}
However, when executing the project, I get an "Access Violation Error" when I try to acceess the array via the **array pointer. This problem does not occur if the array data is
dynamic. Is there any way to sort this problem out (I am not allowed to change the array data from static to dynamic)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
静态数组不是指向指针的指针——整个数组是一个巨大的数据块,并且可以使用单个指针(即指向数组基址的指针)进行寻址。因此
是不正确的,因为您正在取消引用数组内的数字。 (您需要强制转换的事实也应该引发危险信号,因为数组会隐式转换为适当的指针类型。)
这就是为什么常见短语“数组只是指针”是不正确的;对于单维数组来说,它是一半正确的,但对于多维数组来说,它是完全错误的。如果需要使用两个索引,请将行乘以行大小,然后使用指针将列和索引添加到数组中,将单个索引转换为行列索引。
Static arrays are NOT pointers to pointers -- the entire array is a single huge chunk of data, and addressable with a single pointer, namely, the pointer to the base of the array. Hence
is incorrect, because you're dereferencing a number inside the array. (The fact that you needed to cast also should've raised a red flag, since arrays are implicitly converted to the appropriate pointer types.)
That's why the common phrase "arrays are just pointers" is incorrect; it's half-true for single-dimensional arrays, but completely false with multidimensional arrays. If you need to use two indices, convert a single index into a row-column index by multiplying the row by the row size, then adding the column and indexing into the array with a pointer.