简体   繁体   English

头文件导致函数调用后原始数组出现问题

[英]Header file causes problems with the original array after function call

I created a header file called primes.h What I want is to call a function generate_primes() defined in this header file to fill an array with a determined number of prime numbers. 我创建了一个名为primes.h的头文件。我要调用的是在此头文件中定义的函数generate_primes(),用确定数量的素数填充数组。 So to test if everything works fine, I first printed the elements of the array from 'inside' the header file' wich works just fine. 因此,要测试一切是否正常,我首先从头文件的“内部”打印了数组的元素,直到一切正常。 Then I tried printing them from outside the header file, in the program including the header file but It's not working, and the program just stops after printing a few elements. 然后,我尝试从头文件之外的程序(包括头文件)中打印它们,但是它不起作用,并且程序在打印了几个元素后才停止。 Why is this unproper behaviour? 为什么这种不当行为? And how can I do this the right way. 以及我如何才能正确地做到这一点。 Thank's for helping. 感谢您的帮助。

The header file : 头文件:

int generate_primes(const unsigned long long n, unsigned long long*prime) 
{

    try
        {
            prime = new unsigned long long[n]; 
        } 
    catch(const std::bad_alloc&e) {
        std::cerr << e.what(); 
        exit(EXIT_FAILURE);  
    }

    prime[0] = 2, prime[1] = 3, prime[2] = 5; 

    unsigned long long p;
    unsigned long long index = 3;

    for (p = 7; index < n; p += 2)
        {
            short isPrime = 1; 
            unsigned long long test_limit = (unsigned long long) sqrt(p); 

            for (int i = 1; prime[i] <= test_limit && i < index; i++)
                {
                    if (!(p%prime[i]))
                        {
                            isPrime = 0; 
                            break;  
                        }   
                } 
            if (isPrime) prime[index++] = p; 
        }

    //everything works fine when I print from inside the header file 
    /*for (int i = 0; i < n; i++)
      {
      if (i && i % 7 == 0) std::cout << '\n'; 
      std::cout << prime[i] << "\t\t"; 
      }
    */
    return 1; 
}

My program : 我的程序:

#include <iostream>
#include <cmath>
#include <vector>
#include <new>
#include <cstdlib>
#include "primes.h"

int main(){
    unsigned long long n = 100;//example  
    unsigned long long *prime;   
    generate_primes(n, prime); 

    //but printing from here causes problems 
    //isn't the array now filled after calling the above function ? 
    for (unsigned long long i = 0; i < n; i++) 
        {
            if (i && i % 5 == 0) std::cout<< '\n'; 
            std::cout << prime[i] << "\t"; 
        } 

    return 0; 
}

The problem is that the parameter prime is being passed by value, not by reference. 问题在于参数prime是通过值而不是通过引用传递的。 So when generate_prime assigns: 因此,当generate_prime分配时:

prime = new unsigned long long[n];

this only assigns to the local variable prime , not the caller's variable. 这只会分配给局部变量prime ,而不是调用者的变量。 You need to pass the parameter by reference so that the assignment will be visible to main() . 您需要通过引用传递参数,以便对main()可见分配。

int generate_primes(const unsigned long long n, unsigned long long*&prime) 

That's not a header file, it's a bunch of code. 那不是头文件,而是一堆代码。 If you want to separate that code it should be in another .cpp file. 如果要分隔该代码,则应将其放在另一个.cpp文件中。

An associated .h would look like this: 关联的.h如下所示:

#include <cmath>
#include <vector>
#include <new>

int generate_primes(const unsigned long long n, unsigned long long*prime);

Then you'd have generate_primes.cpp or something like it: 然后,您将拥有generate_primes.cpp或类似的东西:

 #include "generate_primes.h"

 int generate_primes(const unsigned long long n, unsigned long long*prime) {
   // (function body)
 }

To build your application you'd need to compile both .cpp files and link them together with the required libraries. 要构建您的应用程序,您需要编译两个.cpp文件,并将它们与所需的库链接在一起。

The value of the uninitialized pointer prime is an argument to the call of generate_primes. 未初始化的指针prime的值是generate_primes调用的参数。 There it is not evaluated but the parameter assigned a new (local) value. 此处不进行评估,但为参数分配了新的(本地)值。 Therefore inside the method the Array is accesible. 因此,在方法内部,数组是可访问的。 But the new value is never returned, so in main the value of prime remains unchanged. 但是新值永远不会返回,因此主要的素数值保持不变。

Additionally you should change n from unsingned long long to a smaller type for teh sake of the compiler. 另外,出于编译器的考虑,应将n从单数long long更改为较小的类型。

Two possible solutions: a) modify generate_prime so that it return the address of the Array 两种可能的解决方案:a)修改generate_prime,使其返回数组的地址

unsigned long long *prime generate_primes(const unsigned long n) 

b) gíve the address of the pointer as an Argument to the method b)将指针的地址作为方法的参数

int generate_primes(const unsigned long n, unsigned long long **prime) 
{

    try
    {
        *prime = new unsigned long long[n]; 
    } catch (const std::bad_alloc &e) {
    // your code

and

int main(){
    unsigned long n = 100;//example  
    unsigned long long *prime;   
    generate_primes(n, &prime);

    // your Code

    delete[] prime; // free memeory
    return 0; 
}

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

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