简体   繁体   English

如何在不同的 function 中访问存储在动态 memory 中的变量?

[英]How can I access variables stored in the dynamic memory in a different function?

So I made this little piece of code that asks the user the size of an array and the contents of the array (in order) and makes the array in the dynamic memory (heap?).所以我做了一小段代码,询问用户数组的大小和数组的内容(按顺序),并在动态 memory(堆?)中创建数组。

void leesgetallen() {
    int *n = new int();
    cout << " Wat is de lengte van de Array?" << endl;
    cin >> *n;
    int g;
    int *A = new int[*n];
    cout << "Geef de getallen van de Array in stijgende volgorde." << endl;
    for (int i = 0; i < *n; i++) {
        cout << "Geef getal nummer " << i << " :";
        cin >> g;
        A[i] = g;
    }
    cout << "Ter controle, dit is de ingegeven Array: ";
    for (int *pa = A; pa != A + *n; pa++) {
        cout << *pa << " ";
    }
}

On its own this works perfectly.就其本身而言,这非常有效。

However when I then try to use this array (A) and size of said array (*n), it doesn't recognize A and *n.但是,当我尝试使用该数组 (A) 和所述数组的大小 (*n) 时,它无法识别 A 和 *n。 I don't quite understand how I can use these variables as to my understanding if they are in the dynamic memory they should be global?我不太明白如何使用这些变量,就我的理解而言,如果它们在动态 memory 中它们应该是全局的?

The reason I need to access them is because I want to use a different function to calculate the average of an inputted array.我需要访问它们的原因是因为我想使用不同的 function 来计算输入数组的平均值。

like so.像这样。

int gem(int a[], int n) {
    int som = 0;
    for (int *pa = a; pa != a + n; pa++) {
        som += *pa;
    }
    int gemiddelde = som / n;
    cout << "Het gemiddelde van deze array is: " << gemiddelde << endl;
    return gemiddelde;
}


void leesgetallen() {
    int *n = new int();
    cout << " Wat is de lengte van de Array?" << endl;
    cin >> *n;
    int g;
    int *A = new int[*n];
    cout << "Geef de getallen van de Array in stijgende volgorde." << endl;
    for (int i = 0; i < *n; i++) {
        cout << "Geef getal nummer " << i << " :";
        cin >> g;
        A[i] = g;
    }
    cout << "Ter controle, dit is de ingegeven Array: ";
    for (int *pa = A; pa != A + *n; pa++) {
        cout << *pa << " ";
    }
}


int main() {
    leesgetallen();
    gem(A, *n);
    delete *n;
    delete[] A;
}

Can anyone help me out?谁能帮我吗?

ps: all text is in dutch, but that shouldn't really matter I hope. ps:所有文字都是荷兰语,但我希望这并不重要。

Main ways of communicating something from within a function to caller / external:从 function 内部与调用者/外部通信的主要方式:

  • return the variable. return变量。 That's what functions are about, anyways.无论如何,这就是函数的意义所在。 You might return multiple variables using either a std::tuple<> , or simply declare a struct for the return type (preferred for complex types).您可以使用std::tuple<>返回多个变量,或者简单地为返回类型声明一个结构(对于复杂类型来说是首选)。

  • Make it a member function and update the object it's applied to.使其成为成员 function 并更新它所应用的 object。

  • Use an output argument (eg an int*& A ).使用 output 参数(例如int*& A )。 This is usually less preferred over returning the variable;这通常比返回变量更不受欢迎; in the past, it was very common to return eg status code this way.过去,以这种方式返回例如状态码是很常见的。

  • Update a global variable (usually static variable)更新一个全局变量(通常是static变量)

  • Call a function that processes the result.调用处理结果的 function。 This might just update a global, or do something else.这可能只是更新全局,或做其他事情。 The processing function is either known in your function, or is passed to it as a template (or in some cases, function pointer / std::function<> ) argument.处理 function 在您的 function 中是已知的,或者作为模板传递给它(或在某些情况下,function 指针/ std::function<> )参数。 Template argument has the benefit that you don't need to know the type in advance (eg int or long ).模板参数的好处是您不需要提前知道类型(例如intlong )。 It's common to implement factories this way.以这种方式实现工厂很常见。 When it's the last call in your function, it's called continuation passing.当它是 function 中的最后一次调用时,它被称为继续传递。

  • Update the environment (eg a file, or other externals).更新环境(例如文件或其他外部)。 This is especially useful in large systems where there might be multiple instances of your code working together, but is also orders of magnitude slower (for your actual thread) than the other methods.这在可能有多个代码实例一起工作的大型系统中特别有用,但也比其他方法慢几个数量级(对于您的实际线程)。

Note that variables won't be globally visible just because they're dynamically allocated.请注意,变量不会因为它们是动态分配的而全局可见。 You still need to choose a way to have them visible for the caller (or other part of the code where you'd use them).您仍然需要选择一种方法让它们对调用者(或您将使用它们的代码的其他部分)可见。

new int[*n] creates new, global (in a sense), unnamed array, and returns pointer to its beginning. new int[*n]创建新的全局(某种意义上)未命名数组,并返回指向其开头的指针。 That pointer is the only way to access that array.该指针是访问该数组的唯一方法。 But A , the variable you store it in, is local to leesgetallen so can only be accessed from said function.但是您存储它的变量Aleesgetallen的本地变量,因此只能从所述 function 访问。 To overcome that, you can define A and n in main , for example, and pass references (or pointers) to these variables into leesgetallen .为了克服这个问题,例如,您可以在main中定义An ,并将对这些变量的引用(或指针)传递给leesgetallen (Or, as @lorro suggested, return their values in a tuple) (或者,正如@lorro 所建议的那样,在一个元组中返回它们的值)

Also note that n doesn't need dynamic allocation as you know for sure it will be exactly one int for your whole program.另请注意, n不需要动态分配,因为您肯定知道它对于您的整个程序来说恰好是一个int

Thanks guys, I found the solution.谢谢大家,我找到了解决方案。 And understand a lot more about dynamic allocation and memory management.并且更多地了解动态分配和 memory 管理。

Here is the solution for future reference.这是供将来参考的解决方案。

int gem(int a[], int n) {
    int som = 0;
    for (int *pa = a; pa != a + n; pa++) {
        som += *pa;
    }
    int gemiddelde = som / n;
    cout << "Het gemiddelde van deze array is: " << gemiddelde << endl;
    return gemiddelde;
}


void leesgetallen(int *n, int *A) {
    cout << " Wat is de lengte van de Array?" << endl;
    cin >> *n;
    int cn = *n;
    cout << "controle: n = " << *n << endl;
    int g = 0;
    cout << "Geef de getallen van de Array in stijgende volgorde." << endl;
    for (int i = 0; i != cn; i++) {
        cout << "Geef getal nummer " << i + 1 << " :";
        cin >> g;
        A[i] = g;
    }
    cout << "Ter controle, dit is de ingegeven Array: " << endl;
    for (int *pa = A; pa != A + *n; pa++) {
        cout << *pa << " ";
    }
    cout << endl;
}


int main() {
    int n = 0;
    int *A = new int[n];
    leesgetallen(&n, A);
    gem(A, n);
    delete[] A;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM