如何取消引用作为指针的链表节点数据?
how to dereference a linked list node data that is a pointer?
所以我正在创建一个线性链表,我不允许使用静态数组或字符串作为数据成员(仅限动态字符数组)
所以我有我的数据结构:
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)
,因为数组名称类似于指针。
我有点困惑,我可能跑题了,所以任何意见都将不胜感激,谢谢。
当您使用动态内存时,您首先要记住的是如何分配和释放内存。其次,您如何访问该内存。
作为你的问题,除了使用 dereference.
之外,你似乎还想访问它
要从 "normal allocated" struct/class 中获取任何值,您可以使用 .
因此,使用,例如:艺术家姓名,将是:
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);
当你有嵌套指针和"normal allocated":
时是一样的
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
的 内存指针 ,而不是它的 内容 。要访问指针的内容,可以使用 *
运算符。
所以我正在创建一个线性链表,我不允许使用静态数组或字符串作为数据成员(仅限动态字符数组)
所以我有我的数据结构:
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)
,因为数组名称类似于指针。
我有点困惑,我可能跑题了,所以任何意见都将不胜感激,谢谢。
当您使用动态内存时,您首先要记住的是如何分配和释放内存。其次,您如何访问该内存。
作为你的问题,除了使用 dereference.
要从 "normal allocated" struct/class 中获取任何值,您可以使用 .
因此,使用,例如:艺术家姓名,将是:
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);
当你有嵌套指针和"normal allocated":
时是一样的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
的 内存指针 ,而不是它的 内容 。要访问指针的内容,可以使用 *
运算符。