HELP!!BASIC POINTER CONCEPT CONFUSION!!

in node type data structure, can we traverse till 'NULL' and then dynamically add a new struct node there.if so, why doesnn't following work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  // Example program
#include <iostream>

using namespace std;

typedef 
struct btnode
{
    int data;
    struct btnode* ptr;
    
}* btptr;



int main()
{
  btptr S=new struct btnode;
  S->data=7;
  S->ptr=NULL;
  btptr T=S;
  T=S->ptr;
  T=new struct btnode;
  T->data=9;
  if(S->ptr==NULL)
  cout<<"still null";
  else
  cout<<"no";
  
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
include <iostream>

struct btnode { int data; btnode* next ; } ;

btnode* push_back( btnode* first, int value )
{
    if( first == nullptr ) return new btnode { value, nullptr } ;

    btnode* n = first ;
    for(  ; n->next != nullptr ; n = n->next ) ; // traverse to the last node (the one just before the nullptr)

    n->next = new btnode { value, nullptr } ; // add a new node at the end
    return first ;
}

int main()
{
    // note: delete, exception-safety etc. elided for brevity

    btnode* first = nullptr ;

    for( int i = 0 ; i < 16 ; ++i ) first = push_back( first, i*i ) ;

    for( auto n = first ; n != nullptr ; n = n->next ) std::cout << n->data << ' ' ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/4781864f9f25b6c6
Regarding why the original code doesn't work:
1
2
3
    btptr T=S;			// pointer variable T points to same place as S
    T=S->ptr;			// now T points to the same place as S->ptr
    T=new struct btnode;	// now T points to a new btnode 
Topic archived. No new replies allowed.