Search code examples
c++arraysheader-files

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.

So to test if everything works fine, I first printed the elements of the array from 'inside' the header file' which 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. Thanks 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; 
}

Solution

  • The problem is that the parameter prime is being passed by value, not by reference. So when generate_prime assigns:

    prime = new unsigned long long[n];
    

    this only assigns to the local variable prime, not the caller's variable. You need to pass the parameter by reference so that the assignment will be visible to main().

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