我想将一个二维数组传递到我的线程函数中,该函数必须具有参数 (void *args)。当我想在我的函数中遍历数组时,我一直遇到以下错误:
下标值不是数组、指针或 vector sumArrays += args[i][j] ;
我不确定如何解决这个问题。传递给线程函数的值也是整数。
任何帮助都会很棒!
谢谢
最佳答案
除了使用struct
,还可以创建一个具有正确类型的局部变量:
#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);
}
@ian-abbott 建议的 struct
解决方案的好处是可以轻松添加传递给线程的更复杂的数据(例如数组的维度)。
关于c - 将二维数组传递给线程函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40027393/