不能将结构分配给结构的指针

时间:2014-05-04 22:32:35

标签: c++ data-structures

所以我有这个简单的数据结构,我想从中打印所有字符,但我不能将n分配给n.next。我在java中编程了一下,这种事情起作用了。这段代码有什么问题?

#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;
    }
}

4 个答案:

答案 0 :(得分:5)

nNODEstruct noden.nextstruct node *,因此您无法将n.next分配给n

要使其有效,您可以将函数参数更改为:

void printnode(NODE *n) {
    while (n->next != NULL) {
        cout << n->c;
        n = n->next;
    }
}

请注意,我们使用->运算符来访问使用指针指向的结构的成员。

答案 1 :(得分:3)

试试这个:

void printnode(NODE* n){
  while(n->next){
    cout << n->c;
    n=n->next;
  }
}

它使用指针访问NODE

在您的版本中,您正在尝试分配指向非指针类型的指针:

void printnode(NODE n){    
  ...
  n = n.next; // error: n.next is of type NODE*, but n is a non-pointer NODE

答案 2 :(得分:2)

使用指针指向的数据(取消引用指针)

node* p;

你必须输入:

p->next;

这是您的代码的正确版本:

void printnode( NODE *n) {
    while ( n->next != NULL) {
        cout << n->c;
        n = n->next;
    }
}

答案 3 :(得分:0)

您的代码段看起来很像C而不是C ++。 以下是如何编译代码的方法:

#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;
    }
}

......这就是你真正想要的东西,它以最佳效率和正确性完全相同。

#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;
    }
}
相关问题