[英]How to correctly pass an array in a pthread function
What I want to do is to loop through an array using a pthread and print its values.我想要做的是使用 pthread 遍历数组并打印其值。 The problem is that the output is completely different from what I expect.
问题是输出与我期望的完全不同。
#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]);
}
}
For an input of a 2x2 array, for example (0,0): 1, (0,1): 1, (1,0): 1, (1,1): 1 the output will be:对于 2x2 数组的输入,例如 (0,0): 1, (0,1): 1, (1,0): 1, (1,1): 1 输出将是:
Element 0: 4294967297
Element 1: 4294967297
Element 2: 194
Element 3: 8589934594
There clearly is an issue with my use of pointers, but I can't understand it.我使用指针显然存在问题,但我无法理解。
The int *
array is passed in as void *
, then is cast to long int *
. int *
数组作为void *
传入,然后转换为long int *
。 Change your function to:将您的功能更改为:
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]);
}
}
In print_array
you are casting your arg to a long int*
rather than an int*
.在
print_array
您将 arg 转换为long int*
而不是int*
。 This is causing you to read past your buffer.这导致您阅读缓冲区。 Additionally, the first value you are reading
element_array[0]
is probably a combination of your first 2 values.此外,您正在读取的第一个值
element_array[0]
可能是您的前 2 个值的组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.