2维数组指针

4
我将遵循一个示例来实现C语言中的线程:http://ramcdougal.com/threads.html。这个示例使用一个一维数组,但我需要一个动态的二维数组。
如果在main() 中使用 int **array 而不是 int array[ARRAYSIZE],那么它会是什么样子?
我的问题是如何将一个指向二维数组的指针传递给结构体。我的想法是有一个大数组,每个线程只填充该数组的特定区域。
非常感谢!
以下是示例代码:
struct ThreadData {

    int start, stop;
    int* array;

};


void* squarer(struct ThreadData* td) {


    struct ThreadData* data=(struct ThreadData*) td;
    int start=data->start;
    int stop=data->stop;
    int* array=data->array;
    int i;

    for (i=start; i<stop; i++) {
        array[i]=i*i;
    }

    return NULL;
}

int main(void) {

    int array[ARRAYSIZE];
    pthread_t thread[NUMTHREADS];
    struct ThreadData data[NUMTHREADS];
    int i;

    int tasksPerThread=(ARRAYSIZE+NUMTHREADS-1)/NUMTHREADS;

    for (i=0; i<NUMTHREADS; i++) {
        data[i].start=i*tasksPerThread;
        data[i].stop=(i+1)*tasksPerThread;
        data[i].array=array;
    }
    /* the last thread must not go past the end of the array */
    data[NUMTHREADS-1].stop=ARRAYSIZE;

    /* Launch Threads */
    for (i=0; i<NUMTHREADS; i++) {
        pthread_create(&thread[i], NULL, squarer, &data[i]);
    }

    /* Wait for Threads to Finish */
    for (i=0; i<NUMTHREADS; i++) {
        pthread_join(thread[i], NULL);
    }

    /* Display Result */
    for (i=0; i<ARRAYSIZE; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    return 0;
}
2个回答

4

要动态分配二维数组,请使用以下代码:

int** array = malloc(sizeof(int*)*ARRAYSIZE);

在这里,您分配了一个指向int的指针数组,现在您应该为每个指针分配内存:

for(int i = 0;i<ARRAYSIZE;i++)
    array[i] = malloc(sizeof(int)*INNER_ARRAYSIZE);

现在,请使用您的实际数据填写每个条目:

for(int i = 0;i<ARRAYSIZE;i++)
    for(int j = 0;j<INNER_ARRAYSIZE;j++)
        array[i][j]=(i+j);//just for example

请将ThreadData结构更新为使用二维数组:

struct ThreadData {

int start, stop;
int** twoDimArray;//note one more * here

};

只需在这里传递指针:

struct ThreadData data;
data.twoDimArray = array;
data.twoDimArray[0][0] = data.twoDimArray[0][0]*data.twoDimArray[0][0]; //access element at 0,0 and square it

这样做会使所有数据不连续,从而导致缓存性能差。最好使用Iliffe向量策略。 - Joel Falcou
话题发起人正在尝试跟随简单的教程,让我们暂时远离所有可怕的 C 语言东西 :) - Oladya Kane
这不是可怕的C语言问题,而是基本的计算机体系结构。 - Joel Falcou

1

这样想:

当使用一维数组时,startstop是表示1-D空间中坐标的一维向量(而1-D向量可以用整数表示,这就是原始代码使用的内容)。

因此,在2-D数组中,startstop应该是2-D向量:

struct ThreadData
{
  int start[2], stop[2];
  int **array;
}

然后,您将矩形块分配给线程。每个线程在start中获取其块的左上角位置,并在stop中获取其块的右下角位置。

enter image description here

记住,这些块是矩形的,可以是高条状(每个线程1列),或长条状(每个线程1行),也可以是正方形,或在中间的任何位置。您必须通过基准测试来决定哪种形状更快。

从某种意义上说,tasksPerThread 也有两个维度。实际任务数量为 tasksPerThread[0] * tasksPerThread[1]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接