如何将变量从变量传递到指针结构对象?

我试图将设置为随机的变量“ 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;
    }



}

我正在尝试:

  1. val传递n --> HEAD变量
  2. 打印出HEAD -> val

我知道该怎么做#2,但是尝试做#1会导致我在上面所说的其他事情中出现问题。我相信这样做会以某种方式覆盖n的值,但我想知道为什么。任何帮助表示赞赏。

windls2009 回答:如何将变量从变量传递到指针结构对象?

实际上,您需要先分配$query = "INSERT INTO points(value) VALUES (" . implode('),(',$data) . ")"; ,然后才能进行薄的设置,例如给它headnew可以做到这一点。看起来像这样:

val

,稍后,完成后需要delete

Cell *HEAD = new Cell;

但是,这并不理想。如果可以的话,最好使用smart pointers

本文链接:https://www.f2er.com/3168951.html

大家都在问