如何在pthread函数中正确传递数组

时间:2019-06-12 22:51:18

标签: pointers pthreads

我想要做的是使用pthread遍历数组并打印其值。问题在于输出与我期望的完全不同。

#include <unistd.h>
#include <stdio.h>
#include <stdint.h>


int elements = 0;
int n = 0;

void *print_array(void* arg); 


int main()
{   
    /* ----- User input ----- */
    printf("Creating a NxN array. Give N: ");
    scanf("%d", &n);
    int element_array[n*n];
    elements = n*n;

    printf("Give the elements of the %dx%d array \n", n, n);
    for (int i=0; i<n; i++) {
        printf("\n");
        for (int j=0; j<n; j++) {
            printf("(%d,%d): ", i, j);
            scanf("%d", &element_array[i*n+j]);
            //This way the array will be filled line by line
            //eg. for n=4 --> element_array[0..3 then 4..7 then 8..11 then 12..15]
        }
    }


    pthread_t newthread;
    pthread_create(&newthread, NULL, print_array, (void *)element_array);
    pthread_join(newthread, NULL);

    return 0;
}


void* print_array(void* arg) {
    long int *element_array = (long int *) arg;
    for (int i = 0; i < elements; i++) {
        printf("Element %d of the array: %ld\n", i, element_array[i]);
    }

}

对于2x2数组的输入,例如(0,0):1,(0,1):1,(1,0):1,(1,1):1输出将是: / p>

Element 0: 4294967297
Element 1: 4294967297
Element 2: 194
Element 3: 8589934594

使用指针显然存在问题,但我听不懂。

2 个答案:

答案 0 :(得分:0)

int *数组作为void *传入,然后强制转换为long int *。将您的功能更改为:

void* print_array(void* arg) {
    int *element_array = (int *)arg;

    for (int i = 0; i < elements; i++) {
        printf("Element %d of the array: %d\n", i, element_array[i]);
    }
}

答案 1 :(得分:0)

print_array中,您将arg强制转换为long int*而不是int*。这导致您读取缓冲区之外的内容。另外,您正在读取的第一个值element_array[0]可能是前两个值的组合。