所以我正在创建一个线性链表,不允许使用静态数组或字符串作为数据成员(仅限动态字符数组)
所以我有我的数据结构:
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
的内存指针,而不是其内容。要访问指针的内容,可以使用*
运算符。