开发者

Access Violation with static arrays?

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 thr开发者_高级运维eadParameter;
   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)?


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

tp->array = (float **) data;

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜