c++ - 链表箭头运算符

标签 c++ c pointers linked-list

在基本的链表程序中,我通常会实现它:

struct node {
    int info;
    struct node * next;
};

int main() {
    struct node * head = malloc(sizeof(node)*3); //for 3 nodes
    head->info = 1;
    head->next->info = 2;
    head->next->next->info = 3;
    //more code
}

现在,要打印第二个节点的内容,我使用以下语句:

cout<<head->next->info;

我的问题是,除了使用上面的语句之外,是否可以使用以下语句:

cout<<head[1]->info;

最佳答案

My question is, instead of using the above statement, can the following be used:

cout<<head[1]->info;

就您的情况而言,实际上,,因为您的代码不会创建链接列表,而更像是一个数组。一个数组,其中每个元素显然应该有一个指向下一个元素的指针 next,但所有这些指针都未初始化。

使用std::list直到你知道链表是​​如何工作的......然后继续使用它!

关于c++ - 链表箭头运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19477576/

相关文章:

c - "++"操作在 C 中是原子的吗?

c - c中va_arg函数中的变量参数类型

c - K&R 练习 1-9。 Putchar 和 getchar

c++ - 如果已知 void* 分配大小,如何将确切的内存大小传递给 free()

c - 如何在 C 中声明和初始化指向结构的指针数组?

c++ - C4003 : Not enough actual parameters for macro in C++

c++ - 如何使用 css 更改 QStackedWidget 中 QWidget 的背景颜色?

c++ - C中的二维数组如何变成一维数组?

c++ - 如何从文件中读取数据 block ,然后从该 block 读取到 vector 中?

c++ - 从 Visual Studio 启动另一个项目