【发布时间】:2018-11-27 08:10:03
【问题描述】:
我创建一个数组:
unsigned short* array = malloc(sizeof(unsigned short)*N);
给它赋值:
for(i=0; i<N; i++){
array[i] = rand()%USHRT_MAX;
}
将其转换为 void* 并将其传递给工作线程,该线程将在数组中找到最大值:
pthread_create(&threads[0], NULL, findMax, (void*)&array);
看起来像这样:
void* findMax(void* arg){
int i = 0;
unsigned short max = 0;
unsigned short* table = (unsigned short*)arg;
for(i=0;i<N;i++){
if(table[i]> max){
max = table[i];
}
}
printf("Max: %d\n", max);
}
问题在于数组中分配的数字格式错误。例如 N 个随机生成的数字:3664 50980 37495 12215 33721,此循环将解释为以下数字:
table[0] = 28680
table[1] = 2506
table[2] = 5
table[3] = 0
table[4] = 32736
以 5 和 0 作为数组中第 2 和第 3 位的重复模式。
我显然超出了一些内存界限,这里发生了什么,我该如何解决?
【问题讨论】:
-
当你在pthread_create中传递参数时,变量已经是一个指针,所以你应该传递(void*)array
-
标签: c casting void-pointers