Expression must have a constant value

I'm having some serious issues with my introduction to pointers assignment. The assignment is not complete, but I can't get past the return of a pointer in the function createArray. There is something wrong but no errors coming up. It won't even output my getSize function even though it's on the top of my main.

Please help. I'm thinking my problem is I can't create a constant correctly. I don't know if the way I'm doing it by creating a variable with getSize then assigning it to a constant is working correctly.




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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
using namespace std;

int getSize();
int *createArray(int);
void fillArray(int *, int);

int main()
{
    //get size
    const int SIZE = getSize();
    
    //create array
    int *ptrarray = NULL;
    ptrarray = createArray(SIZE);
    
    //fill array
    fillArray(ptrarray, SIZE);
    
    for (int index = 0; index < SIZE; index++)
        cout << ptrarray[index];
    return 0;
}

int getSize()
{
    int size;
    cout << "What how many elements would you like in the array?";
    cin >> size;
    return size;
}

int *createArray(int size)
{
    int array[size];
    int *ptr = NULL;
    ptr = array;
    return ptr;
}

void fillArray(int *ptr, int size)
{
    srand((unsigned)time(NULL));
    
    for(int index = 0; index < size; index++)
    {
        ptr[index] = (rand() % 31) + 65;
    }
}
Last edited on
There are at least two problems with the createArray function.

1. array is a local variable and will no longer exist after the function has ended.
2. The size of an array needs to be a compile-time constant.

The only way you can create an array with a non-fixed size is to use the new keyword.

1
2
3
4
int *createArray(int size)
{
    return new int[size];
}

When you create something with new it will stay "alive" until you explicitly use delete (If you don't use delete you'll have memory leak) so this will fix the first problem as well.


It's a bit cumbersome having to keep track of pointers, the size, and call delete, etc. so to make it easier I can strongly recommend using std::vector instead of arrays. It might look a bit complicated at first but it's a very useful tool, I promise.

http://www.cplusplus.com/reference/vector/vector/
Topic archived. No new replies allowed.