C
In C99 and newer standards, you can use VLAs:
int len = ask_length_from_user();
int array[len];
for (int i = 0; i < len ; ++i) array[i] = i;
Note that with VLAs, you should be careful about the size, because VLA will be stored in stack, which is often quite limited (only megabytes, instead of gigabytes of max heap).
Perhaps better is to use heap:
int len = ask_length_from_user();
int *array = malloc (sizeof(int) * len);
if (!array) exit(1); // malloc failed
for (int i = 0; i < len ; ++i) array[i] = i;
Note how you can access allocated memory with same syntax as you would access an array. Also, you can resize memory allocated with malloc
:
int tmplen = ask_length_from_user();
int *tmparr = realloc(array, sizeof(int) * tmplen);
if (tmparr) {
array = tmparr;
// note: following loop doesn't do anything if len >= newlen
while(len < tmplen) array[len++] = len;
}
// else realloc failed, keep original array and len
Finally, with malloc
ed memory, remember!
free(array);
C++
You should use for example std::vector:
int len = ask_length_from_user();
std::vector<int> array;
for (int i = 0; i < len ; ++i) array.push_back(i);
// alternatively, you can resize the array and use indexes like in C snippets:
array.resize(len);
for (int i = 0; i < len ; ++i) array[i] = i;
And code for resize, just with push_back
:
int tmplen = ask_length_from_user();
if (tmplen < len) {
len = tmplen;
array.resize(tmplen);
} else {
while (len < tmplen) array.push_back(len++);
}
As you can see, C and C++ codes are totally different. They are different languages, and it seldom makes sense to ask same thing about both. C code (except VLAs in current standard C++) would work in C++, but doing that is not a good idea, it's not good C++, and at least you should avoid malloc
and use new
(though it does not support resizing nicely).