divisorz

I want to create a function which will take a number and allocate an array which will be 'filled' with its divisors. Now, after the line:
cout << number << ' ';
the program crashes. I can't understand why. Can anyone help me here? Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void func(int n)
{
    int *arr = 0, number;
    GetDivisors(n, arr, number);
    cout << number << ' ';
    for(int i = 0; i < number; i++)
        cout << arr[i];
    delete arr;
}

void GetDivisors(int n, int *divisors, int &n_elem)
// There may be a more efficient way of doing this, but this does the job good enough
{
    n_elem = 0;
    for(int i = 1; i <= n; i++)
        if(n % i == 0)
            n_elem++;

    divisors = new int[n_elem];
    n_elem = 0;

    for(int i = 1; i <= n; i++)
    {
        if(n % i == 0)
        {
            divisors[n_elem] = (n / i);
            n_elem++;
        }
    }
}
Last edited on
http://bytes.com/topic/c/answers/757897-allocating-memory-pointer-passed-another-function
This thread explains why you're getting a segfault and how to accomplish what you want.

Of course you should use new and delete in lieu of malloc and free.
Or simply
void GetDivisors(int n, int *&divisors, int &n_elem);

Thank you. :)
Topic archived. No new replies allowed.