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:
- pass the
valvariable fromn --> HEAD - 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.
HEADis not updated. Did you check that the code as posted in your question still produces the results you describe?