我的 C++ 语法很生疏。这是我的代码:
/*
Add hdr of length length to the msg.
*/
void Message::msgAddHdr(char *hdr, size_t length)
{
char *temp; //temp to iterate through hdr
size_t i; //iterator
temp=hdr;//Set temp to beginning of header
//Iterate temp to the last letter of the header
for(i=0; i < length; i++)
{
*temp = temp -> next;
}
//Delete the null terminator after the hdr
delete *temp -> next;
//Set what temp is pointing to (which should be the last letter of the
//header) to point to the msg.
*temp -> next = Message.msg;
//Delete temp when you're done with it?
delete temp;
return;
}
我遇到的两个大问题是:
- 如何更改指针的指针所指向的位置? (即 temp 指向 hdr 内部的一个指针,它需要指向一个新位置)我有 "*temp->next 因为缺乏正确的语法知识。
我在 header 后添加了
Message.msg
,但是调用此方法的方式是这样的:m->msgAddHdr(h1,5);
我如何在我的方法中使用那个 m?
最佳答案
for(i=0; i < length; i++)
{
*temp = temp -> next;
}
我认为您的意思是将 temp
增加 length
元素。这是通过
temp += length;
char*
上没有可用的方法。
//Delete the null terminator after the hdr
delete *temp -> next;
不能在这里调用delete
。您只需对使用 new
制作的内容调用 delete
。此外,您不能删除 char*
C 字符串中间的字符。
//Set what temp is pointing to (which should be the last letter of the
//header) to point to the msg.
*temp -> next = Message.msg;
不太确定您要在这里做什么。没有next
。我认为我们需要更多地了解 Message.msg
。目前我们甚至不知道它是什么类型。
//Delete temp when you're done with it?
delete temp;
您没有使用 new
分配 temp
,因此您不能也不应该对其调用 delete
。
return;
不需要这样做,void 函数会在到达末尾时执行此操作。
更一般地说,我认为您需要回到教科书并复习基础知识。由于您使用的是 C++,因此您可以使用更高级别的结构,例如 std::vector
和 std::string
。一旦你开始使用 C++,你真的应该完全避免 char*
工作。它很乱而且很难正确。 native C++ 构造要简单得多。
我强烈建议您放弃所有这些代码,并尝试提出一个基于 std::string
的版本。
关于c++ - 指针和 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7787300/