+ 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.

21st Mar 2018, 6:51 PM
AnkaJ
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
21st Mar 2018, 7:04 PM
Alex
Alex - avatar
+ 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 ^^
21st Mar 2018, 8:02 PM
Alex
Alex - avatar
+ 1
Thank you soo much for the fast answer. That is way better than the solutions I found! 👍
21st Mar 2018, 7:37 PM
AnkaJ
+ 1
Just for completion here is a how-to for multidimensional arrays: http://www.equestionanswers.com/c/dynamic-2d-3d-array.php
21st Mar 2018, 7:41 PM
Alex
Alex - avatar
+ 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...
21st Mar 2018, 7:52 PM
AnkaJ