[英]Can't assign structure to pointer of structure
So i have this simple data structure and I want to print all characters from it, but I can't assign n to n.next. 所以我有这个简单的数据结构,我想从中打印所有字符,但是我不能将n赋给n.next。 I programmed in java a bit, and this kind of things worked.
我用Java编程了一下,这种事情行得通。 What is wrong with this code?
此代码有什么问题?
#include <iostream>
using namespace std;
struct node{
char c;
struct node *next;
struct node *prev;
};
typedef struct node NODE;
void printnode(NODE n){
while(n.next){
cout << n.c;
n=n.next;
}
}
n
is NODE
which is struct node
but n.next
is struct node *
so you can't assigne n.next
to n
. n
是NODE
,它是struct node
但n.next
是struct node *
因此您不能将n.next
分配给n
。
To makes it works you can change you're functions argument to : 为了使它起作用,您可以将您的functions参数更改为:
void printnode(NODE *n) {
while (n->next != NULL) {
cout << n->c;
n = n->next;
}
}
Note that we use the ->
operator to access the members of a struct pointed to with a pointer. 注意,我们使用
->
运算符来访问用指针指向的结构的成员。
Try this: 尝试这个:
void printnode(NODE* n){
while(n->next){
cout << n->c;
n=n->next;
}
}
It uses a pointer to access NODE
. 它使用指针访问
NODE
。
In your version, you are are trying to assign a pointer to a non-pointer type: 在您的版本中,您正在尝试将指针分配给非指针类型:
void printnode(NODE n){
...
n = n.next; // error: n.next is of type NODE*, but n is a non-pointer NODE
To use a data pointed by a pointer (to dereference a pointer) 使用指针指向的数据(取消对指针的引用)
node* p;
you have to type: 您必须输入:
p->next;
This is the correct version of your code: 这是您的代码的正确版本:
void printnode( NODE *n) {
while ( n->next != NULL) {
cout << n->c;
n = n->next;
}
}
Your code snippet looks a lot like C rather than C++. 您的代码段看起来很像C,而不是C ++。 Here's how you get your code to compile:
您可以通过以下方式来编译代码:
#include <iostream>
using namespace std;
struct node{
char c;
struct node *next;
struct node *prev;
};
typedef struct node NODE;
void printnode(NODE* n){
while(n->next){
cout << n->c;
n=n->next;
}
}
...and here's what you really want, which does exactly the same thing with optimal efficiency and correctness. ...这就是您真正想要的,它以最佳的效率和正确性来做完全相同的事情。
#include <iostream>
#include <forward_list>
using namespace std;
using mylist_t = std::forward_list<char>;
void printList(const mylist_t& list){
for(const auto& c : list) {
cout << c;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.