2012-02-15 80 views
5

我在Linux上進行編程非常新穎。我正在嘗試在我的任務之一中實現消息隊列。但我無法做到。代碼如下:Linux上的C編程新手,被困在類型轉換中

#include <stdio.h> 
#include <sys/ipc.h> 
#include <sys/msg.h> 
#include <linux/sched.h> 
#include <stdlib.h> 
#include <string.h> 

typedef long MSISDN; 
typedef struct 
{ 
    long mtype; 
    long mtext; 
}msgbuf; 

void init(int qid,int key) { 
    qid = msgget(key,IPC_CREAT|0666); 
} 

void sendMsg(long t_ype, long buf, int len, int qid) { 

    int length = sizeof(long) + sizeof(MSISDN); 
    msgbuf *p = malloc(length); 
    p->mtype = t_ype; 
    fputc('2',stderr); 
    void* tosend = (void*) buff; 
    fputc('3',stderr); 

    memcpy(p->mtext,tosend,length); 

    fputc('4',stderr); 
    msgsnd(qid,p,length,IPC_NOWAIT); 
    free(p); 
} 



void main() 
{ 
    int qid; 
    int key = 1111; 
    int len= sizeof(MSISDN); 
    long type_1=1; 
    long send = 12345; 

    init(qid,key); 
    fputc('1',stderr); 
    sendMsg(type_1,send,len,qid); 

    getchar(); 
} 

問題是memcpy不起作用。我收到警告:

。警告:傳遞「的memcpy」的參數1時將整數指針,未作施放[默認啓用]

此外,當我運行代碼它得到在一個的memcpy SIGSEGV信號。我想我沒有正確地獲得類型轉換。

+2

參數memcpy'的'1是複製到(一個指針指向一個地址更具體地)的地址。嘗試'&(p-> mtext)'。查看[Mancile on Memcpy](http://www.kernel.org/doc/man-pages/online/pages/man3/memcpy.3.html)。 – Chad 2012-02-15 17:50:24

+0

這條消息(「*使得整型指針沒有轉換*」)並不意味着你應該添加一個轉換。實際上**你不應該添加一個轉換**,而是獲得正確的指針。 – pmg 2012-02-15 17:52:21

+0

'buff'不被任何定義... – sth 2012-02-15 17:53:30

回答

5

這不是類型轉換,它的參數本身。 p->多行文字是很長的,而不是指針。您需要發送的P->多行文字的地址作爲DEST參數memcpy的。你得到了段錯誤,因爲memcpy試圖寫入由p-> mtext指向的內存地址,這顯然不在你的進程地址空間中。

這就是原因 - 因爲這是一個家庭作業,我將離開代碼的固定給你。

+0

非常感謝球員.....現在它的工作..... :) – anshu 2012-02-15 17:58:09

+0

@anshu任何時間,歡迎堆棧溢出;並記得接受解決您的問題的答案。 – Chad 2012-02-15 17:59:10