当我在 main() 之前声明一个函数指针时,我遇到了一个段错误 并为其分配 main 中函数的地址。如果在 main() 之前声明函数指针,实际会发生什么问题??
代码如下:
#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;
}
而当我在 main()
中声明 funptr
时,它会给我正确的输出。想知道到底是什么问题。
问题出在线程 ID 上。我为这两个线程使用了相同的线程 ID“pid1”,并且我试图加入“pid2”,这也导致了段错误。以下是修改后的代码...
#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;
}
最佳答案
funptr
已经是一个函数指针。要将其转换为 void *
,您只需要 (void *)funptr
。您需要具有 void *(*) (void *)
类型的第三个参数,而不是将您的函数转换为 void*
。参见 pthread_create documentation
正如 Santhosh 在评论中所写,SIGSEGV
的原因是 pthread_create()
被作为指向同一 pthread_t
的参数指针>.
关于c - 使用函数指针时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29226025/