首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将二维数组传递给线程函数

将二维数组传递给线程函数
EN

Stack Overflow用户
提问于 2016-10-14 01:28:51
回答 1查看 2.1K关注 0票数 0

我想要将一个2D数组传递给我的线程函数,该函数必须有参数(void *args)。当我想迭代我的函数中的数组时,我总是遇到以下错误:

下标的值不是数组、指针或向量sumArrays += argsi;

我不确定如何绕过这一点。传递给线程函数的值也是整数。

任何帮助都是很棒的!

谢谢

EN

回答 1

Stack Overflow用户

发布于 2016-10-14 02:29:54

除了使用struct,还可以创建一个具有正确类型的局部变量:

代码语言:javascript
运行
复制
#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解决方案的好处是允许轻松添加传递给线程的更复杂的数据(例如数组的维数)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40027393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档