allocate arrays in a function, return pointers

Hi commmunity,

I would like to read vector file data using a function. There exist 2 pointers which point to the arrays test1 and test2 allocated and filled in the function. When calling the function ReadIn I do not know what will be the final size of these arrays. That's why I prefer to allocate the memory inside ReadIn. Furthermore they could become very large why I prefer pointers/references, too.
A deallocation of the arrays should be possible in main.

What's the best way to handle this problem??
Probably you already have noticed that C++ is a new topic for me...

Minimal example:

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
31
32
33
34
35
36
#include "stdafx.h"    // VC++
#include <iostream>
using namespace std;

void ReadIn(int*, int*);

int main()
{
    int *test1, *test2;

    ReadIn(test1,test2);

    cout << test1[5] << endl;
    cout << test2[5] << endl;

    delete [] test1;
    delete [] test2;

    system("pause");
    return 0;
}

void ReadIn(int* a, int* b)
{
    a = new int[100];
    b = new int[100];
    for (size_t i=0;i<99;i++)
    {
        a[i]=i*i;   // arbitrary filling
    }
    for (size_t i=0;i<99;i++)
    {
        b[i]=i;     // arbitrary filling
    }
}


heuni
The problem is that you don't pass that int*'s by reference, but by value. Because of that, in ReadIn(), changes are only made to a and b, and not to the pointers from main(). Change your function declaration + definition to:
 
void ReadIn( int* &a, int* &b );


Also read this: http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Thank you for the quick answer. It helps me much.
I obviously didn't understand a pointer reference correctly...but now its clear!
For everybody here the exactly same problem:
http://www.learncpp.com/cpp-tutorial/74-passing-arguments-by-address/
Topic archived. No new replies allowed.