![](/img/trans.png)
[英]how to pass variables from a temp struct variable for multiple struct variables (permanent storage)
[英]How do I pass variables from a variable to a pointer struct object?
我试图将我设置为随机的变量“val”传递给指针 HEAD,最后我想打印出 HEAD->val。
我尝试使用“HEAD->val = n.val;”直接设置它如您所见,但这会导致 cout 最后打印 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;
}
}
我在尝试着:
n --> HEAD
传递val
变量HEAD -> val
我知道如何做 #2,但尝试做 #1 会导致我上面所说的其他事情出现问题。 我相信我这样做会以某种方式覆盖 n 的值,但我想知道为什么。 任何帮助表示赞赏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.