c++ - 指针和 char*

标签 c++ pointers char

我的 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;
}

我遇到的两个大问题是:

  1. 如何更改指针的指针所指向的位置? (即 temp 指向 hdr 内部的一个指针,它需要指向一个新位置)我有 "*temp->next 因为缺乏正确的语法知识。
  2. 我在 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::vectorstd::string。一旦你开始使用 C++,你真的应该完全避免 char* 工作。它很乱而且很难正确。 native C++ 构造要简单得多。

我强烈建议您放弃所有这些代码,并尝试提出一个基于 std::string 的版本。

关于c++ - 指针和 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7787300/

相关文章:

c++ - 打开对象的实际类型的正确方法是什么?

c++ - 如何在 out.write 中正确声明/使用具有特定 ASCII 代码的字符?

c++ - 尝试使用指向结构 vector 的指针访问结构类型时出错

C函数从文件中读取2个值

c++ - 通过 char 将 .txt 读入 vector 但不忽略空格

c++ - 指向字符串常量的指针

c++ - 验证基本矩阵

c++ - 使用 perl 或 C++ 运行程序

c - 使用指针的指针来引用矩阵

java - 新创建的对象是否给我内存位置或保存新分配的内存位置地址的指针