Reputation: 173
I have a homework problem that I am currently stuck on. The parameters of the problem are as follows. 1.) It must accept a total of 5 integers from a user.
2.) It must have three threads, each of which performs a different function (Average, Minimum, and Maximum).
The problem that I am having is in declaring a global array empty array of 5 elements, and then modifying these elements. Each time I end up with a segfault, telling me that I am doing it incorrectly. The language, by the way, is C, emphatically not C++ (I'm not allowed to use it). If anyone can help me understand what is wrong, I would greatly appreciate it. Also, if it is a duplicate (I looked, nothing I saw addresses these problems), please point me to the question or article where it is addressed Thank you.
Code:
#include <stdio.h>
#include <pthread.h>
void *avgWorker(int in[]);
void *minWorker(int in[]);
void *maxWorker(int in[]);
int main(void)
{
int it, *input;
int in[5];
pthread_t tid1,tid2,tid3;
pthread_attr_t attr1, attr2,attr3;
for (it = 0; it < 5; ++it)
{
printf("Please enter number %d of 5\n", (it + 1));
input[it] = scanf("%d");
}
pthread_attr_init(&attr1);
pthread_attr_init(&attr2);
pthread_attr_init(&attr3);
pthread_create(&tid1, &attr1, avgWorker(in), NULL);
pthread_create(&tid2, &attr2, minWorker(in), NULL);
pthread_create(&tid3, &attr3, maxWorker(in), NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
return 0;
}
void *avgWorker(int in[])
{
int total, avg, it;
total = 0;
for (it = 0; it < 5; ++it)
{
total += in[it];
}
avg = 0;
avg = total / 5;
printf("\n The average value is: %d. \n", avg);
}
void *minWorker(int in[])
{
int min, it;
min = 99999;
for (it = 0; it < 5; ++it)
{
if (in[it] < min)
min = in[it];
}
printf("The minimum value is: %d\n", min);
}
void *maxWorker(int in[])
{
int max, it;
max = -99999;
for (it = 0; it < 5; ++it)
{
if (in[it] > max)
max = in[it];
}
printf("The maximum value is: %d \n", max);
}
Finally, I am compiling this code using gcc, and using the -lpthread flag. Thanks again for any help that can be offered.
Upvotes: 0
Views: 390
Reputation: 46365
Your problem is in the line
input[it] = scanf("%d");
Look up the syntax of scanf
... you need to provide the address where data is stored, so
scanf("%d", input+it);
should be an improvement. Or - as pointed out by @dreamlax, for more readable code
scanf("%d", &input[it]);
Upvotes: 3
Reputation: 15289
This is where it should crash:
input[it] = scanf("%d");
scanf
returns number of fields read, not the data read. Addresses of variables where to store data into should be passed as parameters. Like this:
scanf("%d", &input[it]);
Also input
is just an uninitialized pointer. It's not pointing anywhere (meaningful). I guess you wanted in
, not input
. You don't really need input
variable at all.
Upvotes: 5