Bogdan Zafiescu
Bogdan Zafiescu

Reputation: 21

How do I allocate the size of an array dynamically?

include <stdio.h>

int main() {
   int num = 10;
   int arr[num];
   for(int i = 0; i < num; i++){
     arr[num] = i+1;
   }
}

Some colleague of mine says that this code is not correct and that it is illegal. However, when I am running it, it is working without any errors. And he does not know how to explain why it is working and why I should not code like this. Can you please help me. I am a beginner and I want to learn C.

Upvotes: 2

Views: 3473

Answers (3)

Pierce Griffiths
Pierce Griffiths

Reputation: 753

If you want to dynamically allocate an array of length n ints, you'll need to use either malloc or calloc. Calloc is preferred for array allocation because it has a built in multiplication overflow check.

int num = 10;
int *arr = calloc(num, sizeof(*arr));
//Do whatever you need to do with arr
free(arr);
arr = NULL;

Whenever you allocate memory with malloc or calloc, always remember to free it afterwards, then set the pointer to NULL in order to prevent any accidental, future references, as well as to prevent a double free.

Upvotes: 2

MasterAler
MasterAler

Reputation: 1653

Are you learning C or C++?

Your colleague meant that in that code of yours you are doing something different from what you wanted. It's working because of some additional factors. Because C/C++ standards are evolving and so do compilers as well. Let me show you.

Static array

When you a beginner, it's generally advised to stick to the concept that "a typed array of the compilation-given size" is int arr[N], where N is a constant. You allocate it on the stack and you don't manage it's memory.

In C++11 you can use a constexpr (constant expression), but is still not an arbitrary variable.

In C++14 you can use a "simple expression" for size, but you shouldn't try a lot of it before getting the array concept beforehand. Also, GCC compiler provides an extension to support variable sized arrays, it could be an explanation of "why the code is working at all".

Notice: variable sized arrays are not the same as dynamic arrays. They are not that static arrays from the first chapter of a C/C++ guide book as well.

There also exists a modern approach – std::array<int, 10> but once again, don't start with it.

Dynamic array

When you need to create an array in runtime everything changes. First of all, you allocate it on the heap and either you mange it's memory yourself (if you do not, you get a memory leak, a Pure C way) or use special C++ classes like std::vector. Once again, vectors should be used after getting to know Pure C arrays.

Your colleague must have been meaning something like that:

int* arr = new int[some_variable]; // this is dynamic array allocation
delete[] arr; // in modern C/C++ you can write "delete arr;" as well

So, your compiler made it work in this exact case, but you definitely should not rely on the approach you've tried. It's not an array allocation at all.

TL;DR:

  • In C++ variable length arrays are not legal
  • g++ compiler allows variable length arrays, because C99 allows them
  • Remember that C and C++ are two different languages
  • The piece of code from the question seems to be not doing what you'd wanted it to do
  • As others mentioned, it should be arr[i] = i + 1 instead, you are assigning to the same array item all the time otherwise

Upvotes: 0

anonmess
anonmess

Reputation: 495

While not necessarily illegal, this code won't do what you intend. When you declare an array, you declare the number of items you want to store, in this instance num. So when you declare num = 10 and arr[num] you get an array that can hold 10 integers. C arrays are indexed from 0, so the indices are 0-9, not 1-10. This is probably what they mean by illegal. Since you are writing to arr[num] or arr[10], you are attempting to use memory beyond the memory allocated for the array.

Additionally, if I understand the intent of the program correctly, you want to fill in the array with the numbers 1-10. To do this, you'd need to access each index individually. You're almost there, the only problem being arr[num] = i + 1;. As mentioned before, it is beyond the end of the array. However, you should probably be using i as your index, so arr[i], because this will access each index, 0-9.

Upvotes: 0

Related Questions