I’m trying to create a dynamic memory. The size of the array is determine by the user input. I’m getting the following error,
"expression must have a constant value".
it seems like I’m doing something wrong. Please help me! How can I make this dynamic?
This is what I have so far:
int* IntPtr = NULL;
int main(){
int arraySize;
cout << "How many numbers will be on the list? ";
cin >> arraySize;
IntPtr = new int[arraySize];
Contact list[arraySize]; // <-- expression must be constant
//more code
delete [] IntPtr;
You’re trying to use Variable Length Arrays. Unfortunately, C++ does not allow them. (though some compiles allow them by extension)
What you need instead is to dynamically allocate the array using
new. (and manually deallocate later withdelete)You’re already doing this correctly with:
Now you can do the same with the
listvariable:Alternatively, you can use the
vectorclass, which is often preferred over dynamic arrays.