my code is not running

My code that has to do with pointers is not running properly for some reason?
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
  #include <iostream>
#include <iomanip>
#include <assert.h>
#include <stdlib.h>

using namespace std;

struct Structure;
typedef Structure * structure_pointer;
struct Structure
{
    int f1;
    int f2;
    structure_pointer f3,f4;
};
structure_pointer get_structure(int n, char ch);
void print_structure(structure_pointer p);
void tranverse_structure(structure_pointer p);
int main()
{
    structure_pointer head,p,q;
    head = new Structure;
    head = get_structure(1,'a');
    q=head;
    for(int i=2; i<=10; i++)
    {
        p= get_structure(i, char('a' + -1));
        q-> f3 = p;
        q= q-> f3;
    }
    cout << endl;
    cout << "Tranversing the whole structure " << endl;
    tranverse_structure(head);
    cout << endl;

    return 0;
}

structure_pointer get_structure(int n, char ch)
{
    structure_pointer temp = new Structure;
    assert (temp != NULL);
    temp -> f1 =4;
    temp -> f2 = ch;
    temp -> f3 = NULL;
    temp -> f4 = NULL;
    return temp;
}

void print_structure (structure_pointer p)
{
    cout << endl;
    cout << "f1 = " << setw(2) << (*p).f1 << "f2 = " << p -> f2;
 
    if (p-> f3 !=NULL)
        tranverse_structure (p->f3);
}

void tranverse_structure (structure_pointer p)
{
    structure_pointer head,q;
    tranverse_structure(head);
    p = head;
    
    for(int i=1; i<=10; ++i)
    {
        q=p;
        p = p-> f3;
        delete q;

    }
}
Please explain the "not properly".


This has grotesk memory leak:
1
2
    head = new Structure;
    head = get_structure(1,'a');


Structure::f2 is int. You write char to it. Not an error, but odd.

1
2
3
structure_pointer head; // uninitialized
tranverse_structure(head); // use of uninitialized variable
p = head; // use of uninitialized variable 


1
2
structure_pointer get_structure(int n, char ch)
// unused parameter n 


... and then some.


In short: we cannot see what you expect to be "proper", but we can see many points that should crash and burn.
> int f1;
> int f2;
> structure_pointer f3,f4;
Utterly meaningless variable names.

You might get more clarity if you had say
1
2
3
4
5
struct Structure {
    int numberOfOccurrences;
    char letter;
    structure_pointer prev,next;
};

At least you'd stand a chance of spotting silly mistakes like say
letter += 1; // huh?
prev = next; // huh?


1
2
3
4
void tranverse_structure (structure_pointer p)
{
    structure_pointer head,q;
    tranverse_structure(head);

Because calling yourself recursively without giving yourself an out, will always blow up.
Topic archived. No new replies allowed.