Dynamic Array Allocating Function

I'm currently in the process of writing up a function that allocates two arrays of 100 integers each using this function.

The function has 2 arguments:
1) the # of elements it allocates
2) A pointer defined in main and passed by reference so that when the function allocates the array, the address of that array can be passed back to main.
I'm just not entirely sure I'm going about this the right way and would appreciate some direction via examples.


Note: First attempt is written in main TEMPORARILY
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
 int main(int size){
    
    ////    1st Function
   
        int *pointer = NULL;
        size = 100; //DELETE LATER
        pointer = new int[size];

        int temp;

        for(int counter = 0; counter < size; counter++){
            cout << "ENTER the item " << counter + 1 << endl;
            cin >> temp;

            *(pointer+counter) = temp;
        }

        cout << "The items you have ENTERED are " << endl;
            for(int counter = 0; counter < size; counter++){
            cout <<  "Item " << counter + 1 << " is " << *(pointer+counter) << endl;
    }

    delete []pointer;

}




2nd Function attempt
1
2
3
4
5
int dynAlloc(int& pointer[], int size){
    for (int i = 0; i < size, ++i){
        pointer[i];
    }
}

Here's a minimal example that demonstrates how to pass that pointer by reference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string.h>
  
void myAlloc(char*& ptr, size_t size) {
    ptr = new char[size];
}

int main() {
    size_t nameLength = 64;
    char* name = nullptr;

    myAlloc(name, nameLength);
    strcpy(name, "cplusplus.com");
    delete [] name;
    name = nullptr;
}
@nosol6

In your first snippet, line 15 works, but would more normally be written using array notation:

pointer[counter] = temp;

The same notation would normally be used in line 20.

In your second snippet, line 3 does nothing at all. What is it you intended that line to do?
Topic archived. No new replies allowed.