如何从 int 指针数组中检索值? (上下文:在 pthread_create() 中传递数组)
How do I retrieve values from int array of pointers? (context: passing array in pthread_create())
我在 pthread_create() 中传递了一个 int 数组:
显然我需要投 (void *) 才能工作。
pthread_create(&id1, NULL, sorter, (void *)array1);
在排序函数中:
还有谁能建议一种计算数组大小的方法吗?
void *sorter(void *param){
int *arr = (int *)param; //access that array we passed
for(int i=0;i<array.size;i++){
printf("\n%d",arr[i]);
}
printf("%d",*arr[0]);//throws invalid type argument of unary ‘*’ (have ‘int’) error
pthread_exit(0);
}
这里有一些关于 pthreads 的有用幻灯片 link:
https://courses.engr.illinois.edu/cs241/fa2010/ppt/10-pthread-examples.pdf
传递一个指向包含大小的结构的指针,以及一个指向数组的指针
void *sorter(void *param);
struct sized_array
{
size_t size;
int *data;
}
int main(int argc, char const* argv[])
{
// declare id1 somewhere
int* arr = (int*)malloc(50);
struct sized_array array1 = { 50, ar_ };
pthread_create(&id1, NULL, sorter, (void *)&array1);
// note this will leak memory, this is just a demonstratory example
}
void *sorter(void *param)
{
struct sized_array *arr = (struct sized_array *)param; //access that array we passed
for(int i=0;i<arr->size;i++){
printf("\n%d",arr->data[i]);
}
printf("%d", arr->data[0]); // note i removed the dereference here, as it's the value is an int, not an int*
pthread_exit(0);
}
我在 pthread_create() 中传递了一个 int 数组: 显然我需要投 (void *) 才能工作。
pthread_create(&id1, NULL, sorter, (void *)array1);
在排序函数中:
还有谁能建议一种计算数组大小的方法吗?
void *sorter(void *param){
int *arr = (int *)param; //access that array we passed
for(int i=0;i<array.size;i++){
printf("\n%d",arr[i]);
}
printf("%d",*arr[0]);//throws invalid type argument of unary ‘*’ (have ‘int’) error
pthread_exit(0);
}
这里有一些关于 pthreads 的有用幻灯片 link:
https://courses.engr.illinois.edu/cs241/fa2010/ppt/10-pthread-examples.pdf
传递一个指向包含大小的结构的指针,以及一个指向数组的指针
void *sorter(void *param);
struct sized_array
{
size_t size;
int *data;
}
int main(int argc, char const* argv[])
{
// declare id1 somewhere
int* arr = (int*)malloc(50);
struct sized_array array1 = { 50, ar_ };
pthread_create(&id1, NULL, sorter, (void *)&array1);
// note this will leak memory, this is just a demonstratory example
}
void *sorter(void *param)
{
struct sized_array *arr = (struct sized_array *)param; //access that array we passed
for(int i=0;i<arr->size;i++){
printf("\n%d",arr->data[i]);
}
printf("%d", arr->data[0]); // note i removed the dereference here, as it's the value is an int, not an int*
pthread_exit(0);
}