简体   繁体   中英

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. I programmed in java a bit, and this kind of things worked. 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 .

To makes it works you can change you're functions argument to :

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 .

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++. 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM