I get a segmentation error when I declare a function pointer before main () and assign it the function address inside main. What is the actual problem that occurs if a function pointer is declared before main () ??
The code is below:
#include <stdio.h>
#include <pthread.h>
void fun1(char *str)
{
printf("%s",str);
}
void (* funptr)(char *);
int main()
{
char msg1[10]="Hi";
char msg2[10]="Hello";
pthread_t pid1, pid2;
funptr=&fun1;
pthread_create(&pid1,NULL,(void *)(*funptr),(void *)msg1);
pthread_create(&pid1,NULL,(void *)(*funptr),(void *)msg2);
pthread_join(pid1,NULL);
pthread_join(pid2,NULL);
return 0;
}
If I declare funptrinside main(), it gives me the correct conclusion. I would like to know what the problem is.
The problem is with the thread id. I used the same stream identifier "pid1" for both streams, and I tried to join "pid2", which also led to a segmentation error. Below is the straightened code ...
#include <stdio.h>
#include <pthread.h>
void fun1(char *str)
{
printf("%s",str);
}
void (* funptr)(char *);
int main()
{
char msg1[10]="Hi";
char msg2[10]="Hello";
pthread_t pid1, pid2;
funptr=&fun1;
pthread_create(&pid1,NULL,(void *)(*funptr),(void *)msg1);
pthread_create(&pid2,NULL,(void *)(*funptr),(void *)msg2);
pthread_join(pid1,NULL);
pthread_join(pid2,NULL);
return 0;
}
source
share