我试图将设置为随机的变量“ val”传递给指针HEAD,最后我要打印出HEAD-> val。
我尝试使用“ HEAD-> val = n.val;”直接设置它如您所见,但这会导致打印10个随机数最后出现提示。
#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;
}
}
我正在尝试:
- 从
val
传递n --> HEAD
变量 - 打印出
HEAD -> val
我知道该怎么做#2,但是尝试做#1会导致我在上面所说的其他事情中出现问题。我相信这样做会以某种方式覆盖n的值,但我想知道为什么。任何帮助表示赞赏。