我有这个巨大的头文件average.h
其中包含4个数组。我想通过使用线程分别计算4个数组的平均值来计算头文件的平均值。 运行时出现分段错误,所以我猜如何计算数组的长度有问题。我被告知,计算float**
的大小是不可能的,那么我应该怎么做呢?计算数组的大小来计算使用线程的平均值
这里是我的代码:
/*
* File: main.c
* Author: thomasvanhelden
*
* Created on June 15, 2014, 5:34 AM
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "average.h"
void* calc(void* param) {
float** array = (float**) param;
int size = sizeof(*array)/sizeof(float*);
int i;
float sum = 0;
float* average;
for (i = 0; i < size; i++) {
sum += *array[i];
}
*average = sum/size;
return average;
}
/*
*
*/
int main(int argc, char** argv) {
pthread_t t1, t2, t3, t4; // thread handlers
int res1, res2, res3, res4; // results of creating/joining the threads
void *avg1, *avg2, *avg3, *avg4; // results of the threads as void*
float *result1, *result2, *result3, *result4; // results of the threads as flaot*
// create the threads
res1 = pthread_create(&t1, NULL, calc, a1);
res2 = pthread_create(&t2, NULL, calc, a2);
res3 = pthread_create(&t3, NULL, calc, a3);
res4 = pthread_create(&t4, NULL, calc, a4);
// check for errors creating the threads
if (res1 || res2 || res3 || res4) {
printf("Something went wrong creating the threads!\n");
return 1;
}
// wait for the threads to finish and get the result
res1 = pthread_join(t1, &avg1);
res2 = pthread_join(t2, &avg2);
res3 = pthread_join(t3, &avg3);
res4 = pthread_join(t4, &avg4);
// check for errors joining the threads
if (res1 || res2 || res3 || res4) {
printf("Something went wrong joining the threads!\n");
return 1;
}
// void* to float*
result1 = (float*) avg1;
result2 = (float*) avg2;
result3 = (float*) avg3;
result4 = (float*) avg4;
// print the result, should be
printf("The average is: %f", (*result1 + *result2 + *result3 + *result4));
return (EXIT_SUCCESS);
}
显示数组的声明。 – user694733
这工作?我相信下面的语句会给你1总是在32位平台上指针的大小总是4个字节:int size = sizeof(* array)/ sizeof(float *); –