简体   繁体   中英

Passing a 2D array to a thread function

I want to pass a 2D array into my thread function that must have parameters (void *args). When I want to iterate through the array in my function, I keep running into the following error:

subscripted value is not an array, pointer, or vector sumArrays += args[i][j] ;

I am not sure how to get around this. The values passed in to the thread function are also integers.

Any help would be awesome!

Thanks

Instead of using a struct , one can also create a local variable with the correct type:

#define ROWS 3
#define COLS 3

/* Sum the values in a 3x3 array. */
/* This would be your thread entry point. */
void sum(void *args) {
    int (*array)[ROWS][COLS] = args; // Declare and initialize a pointer to a ROWSxCOLS array of ints.

    int row;
    int col;
    int total = 0;
    for(row = 0; row < ROWS; row++) {
        for (col = 0; col < COLS; col++) {
            total += (*array)[row][col]; // Access [row][col] from the array pointed to by "array".
        }
    }

    (void) total;
}

int main(int argc, char** argv) {
    int arrayIn[ROWS][COLS] = {
        {0, 1, 2},
        {3, 4, 5},
        {6, 7, 8}
    };

    sum(arrayIn);
}

The struct solution suggested by @ian-abbott has the benefit of allowing the easy addition of more complex data being passed to your thread (such as the dimensions of the array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM