0

I am trying to pass the variable "val" that I have set to be random over to the pointer HEAD and in the end I want to print out HEAD->val .

I've tried setting it directly using "HEAD->val = n.val;" as you can see but that results in the cout at the end from printing the 10 random numbers.

#include <iostream>

#include <stdlib.h>

#include <time.h> 

using namespace std;

struct Cell {
    int val;

    Cell *next;


};




int main()
{

    int MAX = 10;

    srand (time(NULL));

    Cell *c = NULL;

    Cell *HEAD = NULL;

    Cell n;



    for (int i=0; i<MAX; i++) {
        // Use dynamic memory allocation to create a new Cell then initialize the 
        // cell value (val) to rand().  Set the next pointer to the HEAD and 
        // then update HEAD. 

        Cell n = {};
        n.val = rand();
        n.next = HEAD;
        HEAD->val = n.val;



        cout << n.val << endl;
    }



}

I am trying to:

  1. pass the val variable from n --> HEAD
  2. print out HEAD -> val

I know how to do #2 but trying to do #1 is causing problems within other things as I said above. I believe i'm somehow overwriting n's values by doing so but I am wondering why. Any help is appreciated.

2
  • Your Code looks more Like a C code than a C++ code. Commented Nov 4, 2019 at 5:26
  • 1
    Your code does not match your comments. 1) "Use dynamic memory allocation" but there is no dynamic memory allocation. 2) "then update HEAD" but the value of HEAD is not updated. Did you check that the code as posted in your question still produces the results you describe? Commented Nov 4, 2019 at 5:30

1 Answer 1

1

You actually need to allocate the head before you can do thins like give it a val. new can work for this. It would look something like this:

Cell *HEAD = new Cell;

and, later, you need to delete it when you're done with it:

delete HEAD;

Though, this isn't ideal. Better is to make use of smart pointers if you can use them.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.