Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>I can use pointers, but I am a bit afraid of using them.</p> </blockquote> <p>If you need a dynamic array, you can't escape pointers. Why are you afraid though? They won't bite (as long as you're careful, that is). There's no built-in dynamic array in C, you'll just have to write one yourself. In C++, you can use the built-in <a href="http://en.cppreference.com/w/cpp/container/vector" rel="noreferrer"><code>std::vector</code></a> class. C# and just about every other high-level language also have some similar class that manages dynamic arrays for you.</p> <p>If you do plan to write your own, here's something to get you started: most dynamic array implementations work by starting off with an array of some (small) default size, then whenever you run out of space when adding a new element, double the size of the array. As you can see in the example below, it's not very difficult at all: (I've omitted safety checks for brevity)</p> <pre><code>typedef struct { int *array; size_t used; size_t size; } Array; void initArray(Array *a, size_t initialSize) { a-&gt;array = (int *)malloc(initialSize * sizeof(int)); a-&gt;used = 0; a-&gt;size = initialSize; } void insertArray(Array *a, int element) { // a-&gt;used is the number of used entries, because a-&gt;array[a-&gt;used++] updates a-&gt;used only *after* the array has been accessed. // Therefore a-&gt;used can go up to a-&gt;size if (a-&gt;used == a-&gt;size) { a-&gt;size *= 2; a-&gt;array = (int *)realloc(a-&gt;array, a-&gt;size * sizeof(int)); } a-&gt;array[a-&gt;used++] = element; } void freeArray(Array *a) { free(a-&gt;array); a-&gt;array = NULL; a-&gt;used = a-&gt;size = 0; } </code></pre> <p>Using it is just as simple:</p> <pre><code>Array a; int i; initArray(&amp;a, 5); // initially 5 elements for (i = 0; i &lt; 100; i++) insertArray(&amp;a, i); // automatically resizes as necessary printf("%d\n", a.array[9]); // print 10th element printf("%d\n", a.used); // print number of elements freeArray(&amp;a); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload