我只需要写一个代码来计算一个数组的一半的局部最大值..但是有一些问题与 ponters (?) 我看到
segmentation fault
问题
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#define n 10
struct args {
int index;
int a[n];
};
void * max_locale(void * parameters) {
struct args * pp = parameters;
int max = pp->a[0];
int finalIndex = pp->index + n/2;
for(int i=pp->index; i<finalIndex; i++) {
if((pp->a[i]) > (pp->a[i+1])) {
max = (pp->a[i]);
}
}
return (void *)&max;
}
int main() {
srand(time(NULL));
int array[n];
pthread_t thread1, thread2;
struct args thread1_args, thread2_args;
printf("-beginning of program-\n");
for(int i=0; i<n; i++) {
array[i] = rand() % 101;
printf("%d ", array[i]);
}
for(int i=0; i<n; i++) {
thread1_args.a[i] = array[i];
thread2_args.a[i] = array[i];
}
int * thread1_returnValue;
int * thread2_returnValue;
thread2_args.index = 0;
thread2_args.index = n/2;
printf("\n Find MAX... \n");
pthread_create(&thread1, NULL, &max_locale, &thread1_args);
pthread_create(&thread2, NULL, &max_locale, &thread2_args);
pthread_join(thread1, (void **) & thread1_returnValue);
pthread_join(thread2, (void **) & thread2_returnValue);
printf("Max 1:%d Max 2:%d \n", *thread1_returnValue, *thread2_returnValue);
return 0;
}
这是输出:
-beginning of program-
98 28 73 5 10 100 23 63 25 60
Find MAX...
zsh: segmentation fault ./15-4-23
我试图用 void * 函数返回 int, 如果我可以在
pthred_create
函数中传递不同的参数,那就容易多了