我正在使用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;
}
是這僅在C++或用C以及 – 2009-11-03 19:27:08
在C以及真。雖然C沒有引用,所以你不能通過引用傳遞 - 只有指向指針的指針。 – 2009-11-03 19:29:26