2009-11-03 85 views
0

我正在使用Qt Creator 4.5與GCC 4.3我遇到以下問題,我不確定是Qt或C++相關:我調用一個函數,將char *作爲輸入參數。在該函數內部,我進行動態分配,並將地址分配給char *。問題是函數返回時它不再指向這個地址。指針不會返回指定地址

bool FPSengine::putData (char CommandByte , int Index) 
{ 
    char *msgByte; 
    structSize=putDatagrams(CommandByte, Index, msgByte); 
} 

int FPSengine::putDatagrams (char CommandByte, int Index, char *msgByte) 
{ 
    int theSize; 

    switch (CommandByte) { 

    case (CHANGE_CONFIGURATION): { 
     theSize=sizeof(MsnConfigType); 
     msgByte=new char[theSize]; 

     union MConfigUnion { 
     char cByte[sizeof(MsnConfigType)]; 
     MsnConfigType m; 
     }; 

     MConfigUnion * msnConfig=(MConfigUnion*)msgByte; 

     ...Do some assignments. I verify and everything is OK. 
    } 
    } 
    return theSize; 
} 

當我回到它含有比putDatagrams()分配一個完全不同的地址指針。爲什麼?
...

好THX我明白我的錯誤(新手的錯誤:()。當發送一個指針作爲輸入參數的功能,你把你的數據的地址,但不是你的指針的地址, 。你不能讓指針指向別的地方......它實際上是一個本地副本像指數數據將問題而與使用一個char *的返回成功地的唯一情況是通過函數調用之前分配內存:

bool FPSengine::putData (char CommandByte , int Index) 
{ 
    char *msgByte; 
    msgByte=new char[sizeof(MsnConfigType)]; 
    structSize=putDatagrams(CommandByte, Index, msgByte); 
} 

int FPSengine::putDatagrams (char CommandByte, int Index, char *msgByte) 
{ 
    int theSize; 

    switch (CommandByte) { 

    case (CHANGE_CONFIGURATION): { 
     theSize=sizeof(MsnConfigType); 

     union MConfigUnion { 
     char cByte[sizeof(MsnConfigType)]; 
     MsnConfigType m; 
     }; 

     MConfigUnion * msnConfig=(MConfigUnion*)msgByte; 

     ...Do some assignments. I verify and everything is OK. 
    } 
    } 
    return theSize; 
} 

回答

3

有兩種方式傳遞按值方式(C風格):

int FPSengine::putDatagrams (char CommandByte, int Index, char **msgByte) 

注二等*msgByte,然後01的內,這樣做:

*msgByte = new char[theSize]; 

事實上,在功能,你現在有msgByte任何地方,使用*msgByte。當調用putDatagrams(),做到:

structSize=putDatagrams(CommandByte, Index, &msgByte); 

而第二種方式,因爲你在C++的時候,你可以通過使用按引用。只需將putDatagrams()的簽名更改爲:

int FPSengine::putDatagrams (char CommandByte, int Index, char * &msgByte) 

而且您應該很好。在這種情況下,你不應該需要修改putDatagrams()例行內來電或任何東西。

2

嗯,是的。在C++中的一切,默認情況下,按值傳遞。在呼叫putDatagrams(a, b, c)參數由發送價值 - 你不希望在代碼分配給index在調用點改變b值。你msgByte=new char[theSize];只是分配給本地變量msgByte,覆蓋在傳遞的值。

如果你想改變一個傳遞的參數使得調用點變量的變化,你需要按引用傳遞,或(在。這種情況下)傳遞一個「指針pointer`(和順從掉第一指針,分配給實際的指針)

+0

是這僅在C++或用C以及 – 2009-11-03 19:27:08

+1

在C以及真。雖然C沒有引用,所以你不能通過引用傳遞 - 只有指向指針的指針。 – 2009-11-03 19:29:26