我想要将一个2D数组传递给我的线程函数,该函数必须有参数(void *args)。当我想迭代我的函数中的数组时,我总是遇到以下错误:
下标的值不是数组、指针或向量sumArrays += argsi;
我不确定如何绕过这一点。传递给线程函数的值也是整数。
任何帮助都是很棒的!
谢谢
发布于 2016-10-13 18:29:54
除了使用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
解决方案的好处是允许轻松添加传递给线程的更复杂的数据(例如数组的维数)。
https://stackoverflow.com/questions/40027393
复制