2014-05-04 70 views
0

所以我有這個簡單的數據結構,我想打印它的所有字符,但我不能指定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; 
    } 
} 
+0

指針是保存地址的完全獨立的類型。它們與它們指向的類型完全不兼容。 – chris

+0

你是什麼意思「我不能指派」?什麼是錯誤? – 4pie0

回答

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 
5

nNODE這是struct noden.nextstruct node *所以你不能assigne n.nextn

要使得它的工作原理,你可以改變你的功能參數:

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

請注意,我們使用->運營商訪問結構的成員指出,用指針。

+0

n.next應該是n->下一個 –

+0

@PhilippClaßen坦克! – rullof

2

要使用由指針指向一個數據(取消引用指針)

node* p; 

你必須鍵入:

p->next; 

這是你的代碼的正確版本:

void printnode(NODE *n) { 
    while (n->next != NULL) { 
     cout << n->c; 
     n = n->next; 
    } 
} 
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; 
    } 
} 
+0

實際上這不是我想要的,因爲這是我的課程。我們正在學習數據結構。不過謝謝 – zbyshekh