2014-10-05 71 views
1
#include<stdio.h> 
#include<string.h> 
#include<pthread.h> 
#include<stdlib.h> 
#include<unistd.h> 
#include<sys/types.h> 

pthread_t id1,id2; 
struct arg{int a[2];}*p; 

void *sum(void *args) 
{ 
    struct arg *b=((struct arg*)args); 
    printf("hello:%d%d",b->a[0],b->a[1]); 
} 

void *mul(void *args) 
{ 
    struct arg *c=((struct arg*)args); 
    printf("hi:%d%d",c->a[0],c->a[1]); 
} 

main() 
{ 
    int err1,err2; 
    p->a[0]=2; 
    p->a[1]=3; 
    err1=pthread_create(&id1,NULL,&sum,(void*)p); 
    err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5); 
} 

我試圖將數據傳遞給使用結構線程.....但我總是得到一個分段錯誤....誰能告訴我什麼是錯我的代碼..線程傳遞參數

+0

假設你設置線程錯誤之前,可以考慮,如果你拋出的線程,只是* *調用是'sum'或'mul'用' (或者視情況而定),你可能會得到相同的結果(在一團火焰中墜毀)。總之,你忘了(或者從來沒有學過)C指針是如何工作的。 – WhozCraig 2014-10-05 06:37:59

回答

1

由於p初始化爲0,您將收到段錯誤。你沒有給它分配任何東西。

+0

@alk是一個全局變量,它按照C標準被初始化爲一個空指針。 – 2014-10-05 14:06:14

+0

絕對!清理... – alk 2014-10-05 14:28:44

2

由於您尚未分配內存給p;它會嘗試將值分配給內存地址0,從而導致段錯誤。

嘗試分配內存使用malloc:

main() 
{ 
int err1,err2; 
struct arg *p=(struct arg *)malloc(sizeof(struct arg)); 
p->a[0]=2; 
p->a[1]=3; 
err1=pthread_create(&id1,NULL,&sum,(void*)p); 
err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5); 
} 
+0

[你不應該投射malloc的結果](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc),但否則一個很好的答案。 – IllusiveBrian 2014-10-05 06:45:37