+ 1
Set array size during run time.
Today while trying out some stuff in C I found out that it is not possible to set the size of an array during runtime in a direct way. Is there any easy way around that? I have asked Google of course, but I don't understand much of the proposed solutions, yet. Please help! đ Here an example of what I would like to do in C: int size; scanf("%d",&size); int array[size]; But this of course does not work.
5 Answers
+ 3
You can use malloc for this.
int* arr = malloc(size*sizeof(int));
This allocates memory depending on the type and number of elements.
You can access the elements in the same way as in normal arrays.
https://code.sololearn.com/cz3aHfpb4MyL/?ref=app
+ 2
It just needs a bit practice. It's not that hard anymore after using it a few times. But no need to hurry. I just wanted to add the link because it felt a bit incomplete to post how to create dynamic arrays in runtime without saying anything about multidimensional arrays ^^
+ 1
Thank you soo much for the fast answer. That is way better than the solutions I found! đ
+ 1
Just for completion here is a how-to for multidimensional arrays:
http://www.equestionanswers.com/c/dynamic-2d-3d-array.php
+ 1
Is it like pointers pointing to pointers? đ” I think I'll need a little bit more time for the second part (the link). I haven't had much practise with pointers yet. - A little bit in Perl but it somehow seemed easier there...