c++ - 如何取消引用作为指针的链表节点数据?

标签 c++ dereference

所以我正在创建一个线性链表,我不允许使用静态数组或字符串作为数据成员(仅限动态字符数组)

所以我有我的数据结构:

struct artists
{
    char* name;
    char* story;
    char* description;

};

和我的节点表示:

struct node //Create our node type for LLL of artists
{
    artists* data;
    node* next;
};

我打算在一个函数内为名称、描述、故事分配内存,但我的问题是我实际上如何取消引用它?

有没有*(temp->data.name)这样的东西?

或者这段代码是否有意义?

name = new char[strlen(artistitle)+1]
strcpy (*(temp->data.name),artistitle)

或者它仍然是 strcpy(temp->data.name,artistitle),因为数组名称的工作方式类似于指针。

我有点困惑,我可能跑题了,所以任何意见都将不胜感激,谢谢。

最佳答案

当您使用动态内存时,您首先要记住的是如何分配和释放内存。其次,您如何访问该内存。
作为你的问题,除了使用取消引用之外,你似乎还想访问它。

要从“正常分配的”结构/类中获取任何值,您可以使用 因此,使用例如艺术家姓名将是:

artists a;
//Suposse you have allocated char pointer here
strcpy(a.name, artistname);

如果您使用的是动态内存,则必须使用 -> 运算符,如下所示:

artists *a;
//Dynamic allocate struct and char pointers
strcpy(a->name, artistname);

当你有嵌套指针和“正常分配”时是一样的:

node n;
//Allocate everything
strcpy(n.data->name, artistname);

//Another way to do it
node *n;
//You have to allocate node too
strcpy(n->data->name, artistname);

当您将指针用作变量时,它会将内存方向存储在它指向 的位置(具有讽刺意味,呵呵)。所以如果你这样做

node *a;
//Allocate it, and do some operations
node *b=a;

您正在复制 a内存指针,而不是它的内容。要访问指针的内容,您可以使用 * 运算符。

关于c++ - 如何取消引用作为指针的链表节点数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46681049/

相关文章:

RuSTLings 线程练习,为什么我不取消引用 Mutex(Struct)?

c - 在 C 中取消引用 malloc() 的返回

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

c++ - 给定一个 DDS 主题名称,是否可以在运行时确定主题类型信息?

c++ - 获取可取消引用类型的 value_type

c++ - 不了解指针和类在此示例中如何协同工作

python - 是否可以取消引用变量 id?

c++ - Release 中的源文件,Debug 中的头文件

c++ - 以递归方式检查每个橄榄球比分,不重复

c++ - 删除指向不完整类型的指针