I get an error of a reference type in this code



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include<iostream>
using namespace std;
struct nodeType
{
    int info;
    nodeType *link;
};
int main()
{
    int *p, *List;
    p = List;
    while(p != NULL)
    cout << p->info<<" ";
    p = p->link;
    cout<<endl;
    
}
nodeType *p, *List;
The code that you did post makes a compiler say:
 In function 'int main()':
14:16: error: request for member 'info' in '* p', which is of non-class type 'int'
15:12: error: request for member 'link' in '* p', which is of non-class type 'int'

Could you show the exact error message from your compiler?


You don't use type 'nodeType' in your code (the main).
I will now reformat your code without changing anything in it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
using namespace std;

int main()
{
    int *p; // p is uninitialized pointer to int
    int *List; // List  is uninitialized pointer to int
    p = List;
    // the value of p is undefined
    while ( p != NULL ) { // this loop will repeat 0 or infinite times
        cout << p->info << " "; // int does not have members
    }

    p = p->link; // int does not have members
    cout << endl;
}


That is your code. Neither we nor the compiler can possibly guess what you mean.
Thanks lastchance.The program compiled okay after l
tpying nodeType *p and nodeType *List.
But when I ran the program nothing was printed out.
When I checked the answers in the book, it says it should run a continuous loop printing the first node in the list. But thanks very much I just have to solve a little problem now.
tpying nodeType *p and nodeType *List.

That will create a pointer to nodeType. Does your code ever actually create a nodeType object? What is that pointer pointing at?
Bopaki wrote:
But when I ran the program nothing was printed out.
When I checked the answers in the book, it says it should run a continuous loop printing the first node in the list.


Mmm. But you never actually put anything in the list to print out. And (as @keskiverto pointed out) you didn't actually initialise pointers to NULL (or nullptr), so you are strictly running with undefined and hoping it is null/zero.
Topic archived. No new replies allowed.