Array bound must be integer constant?

I need to generate an integer array whose bound is set by user input. The array is a sinewave of the standard form Asin(wt) and I want user to input the the number of points in the array to set the sinewave frequency for MCP4725 DAC. I get error 'array bound is not an integer constant before ']' token'.
I can set the array bound in code as const int bound =128 for example and it works but can't figure out how to input bound from the user. Is there a fix or am I missing something?

Is there a fix or am I missing something?

A static array must have a fixed size.

A dynamic array, allocated my malloc(), is sized based on the value supplied to malloc().

Just make sure you understand the significance of dynamically allocating memory, and of the need to free that memory when you are done with it.

In my opinion, dynamic sizing of the array does not make sense. There is an upper limit to the size of the array, static or dynamic. It is usually far better to use a static array, of reasonable size, and work within it’s limits. You’d certainly have to do that with a dynamic array, anyway.

char str[10];

or

const int size = 10;
char str[size];

are both valid. The value between the [] must be a constant.


You could try this - it might pass the compiler. But I have never tried to do it myself.

int nSize = 10;
char str[(const int)nSize];

If you create arrays on the heap then the value does not have to be a constant:

char *str = new char[10];

int size = 10;
char *str = new char[size];

char *str = alloc(size,...);

All these are valid.