17

I'm trying to make a program which

  1. Takes the user input (let's say all of it is int)
  2. Store it in an array without a starting size (i.e. not -> array[5];); and then
  3. Use the information stored in the array for whatever sinister purposes.

I'm asking for help so that I can learn how to do this on my own if needed.

  • How do I make a dynamic array without a set size?
  • How can I use/access/reach the elements in the above array?

Reading just didn't explain enough for me.

I know it's a very noobish question, and yes, I am a noob, but to change that I need some help.

Bruno Vieira
  • 3,884
  • 1
  • 23
  • 35
hilchev
  • 340
  • 1
  • 2
  • 9

5 Answers5

17

For C++:

If you just need a container just use std:vector. It will take care all the memory allocations necessary for you. However if you want to develop your own dynamic container (whatever reasons you have) you have to take care off the memory allocations yourself. That is, when your array grows you have to allocate new memory chunk, copy present array values to the new memory location and add new values to the newly allocated memory. Usually one wraps this kind of logic inside a separate class e.g. GrowingArray(like standard provided vector class)

EDIT

To elaborate more on my answer (given that you are using this for learning purpose):

store it in an array without a starting size (i.e. not -> array[5];)

Here you want to use something like this: int * myDynamicArray; When a user inputs some values you allocate memory chunk where those values are going to be stored: myDynamicArray = new int[5]; with the size of your initial input. I would as well recommend to save the size of the array in some variable: int arraySize = 5; If later on you want to append new values to your myDynamicArray first of all you have to allocate new memory chunk for grown array (current array elements + new array elements). Lets say you have 10 new values coming. Then you would do: int* grownArray = new int[arraySize+10]; this allocates new memory chunk for grown array. Then you want to copy items from old memory chunk to the new memory chunk and add user appended values (I take it you are using this for learning purposes thus I provided you simple for cycle for copying elemts. You could use std:copy or c like memcopy as well):

int i = 0;
for (; i < arraySize; ++i)
   {
   grownArray[i] = myDynamicArray [i];
   }
// enlarge newly allocated array:
arraySize+= 10;
for (; i < arraySize; ++i)
   {
   grownArray[i] = newValues from somewhere
   }
// release old memory
delete[] myDynamicArray;
// reassign myDynamicArray pointer to point to expanded array
myDynamicArray = gronwArray;
Robertas
  • 1,164
  • 3
  • 11
  • 26
15

This is probably the most clever (cryptic excessive STL usage for some) way...

std::vector<int> vec;

// read integers 1 at a time from the user,
// will stop when non-integer input is entered
std::copy(std::istream_iterator<int>(std::cin),
          std::istream_iterator<int>(), 
          std::back_inserter(vec));

// print out the vector
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
David
  • 27,652
  • 18
  • 89
  • 138
10

Here's some code I wrote up in C++ that does the basics.

#include <iostream>

int main(int argc, char *argv[])
{
    int* my_dynamic_array;

    int size;
    std::cin >> size;

    my_dynamic_array = new int[size];

    for (int k=0; k<size; k++)
        my_dynamic_array[k] = k;

    for (int k=0; k<size; k++)
        std::cout << my_dynamic_array[k] << std::endl;

    delete[] my_dynamic_array;

    return 0;
}

Okay, so here's what's going on in this code. We're prompting for the size of the array using std::cin and then using the new keyword to dynamically allocate some memory for the array. There's some details here that make it seem a little weird at first; it's what seems to cause confusion with a lot of new C++ developers.

So first we declared our dynamic array with a pointer instead of the array declaration, e.g. we used int *my_dynamic_array instead of int my_dynamic_array[]. At first this seems kind of trivial, but there's something that you need to understand about what's going on in C and C++.

When you statically declare an array, you are telling the program that you want to set aside that memory for you to use. It's actually there; it's yours for you to start using. When you dynamically create an array, you start with a pointer. Pointers are just a reference to some memory. That memory isn't allocated yet. If you try to access something in it with, say, my_dynamic_array[3], you'll get a nasty error. That's because there's nothing actually in memory at that location (at least nothing that has been given to the program to use).

Also note the use of delete[] instead of delete. That's the way you free up the memory when you're done with the array.

If you're doing this in C, you can pretty much think of this the same way, but instead of new and delete[] you have malloc and free.

Knowing the subtle differences between dynamic arrays and pointers is tricky. It took me a while before I fully understood what was going on. Good luck and keep at it.

austin
  • 5,816
  • 2
  • 32
  • 40
  • And you too, this helped fill in some gaps from the above code :) Thank you! – hilchev Nov 17 '12 at 16:19
  • How does the compiler know how many elements to `delete[]` if the array is dynamic? Does it keep a reference to `size` somehow? – rjh Nov 02 '16 at 13:53
0

In C you can use this method.

int i=0;
int *p;
char c;
int size; 
printf("Enter size :");
scanf("%d",&size); 
int *p=malloc(sizeof(int)*size);
do
{
 printf("Enter Number : ");
 scanf("%d",&p[i]);
 i++;
 printf("Press 'q' or 'Q' to quit or any other key to continue : ");
 scanf("%c",&c);
}
while(c!='q' && c!='Q' && i<=size);
p=realloc(p,i*sizeof(int));

In this way you can free the rest of the memory allocated if the number of integers you want is less than the memory allocated.

Omkant
  • 9,018
  • 8
  • 39
  • 59
0

I hava a suggestion for you. You can use linked list instead of array if you are going todevelop with C

here after an example:

typedef struct linked_list {
    int x,
    struct linked_list *next
} linked_list;

struct linked_list *head = NULL;

void add_element(int x)
{
    struct linked_list *elem;
    elem = malloc(sizeof(struct linked_list));
    elem->x =x;
    elem->next = head;
    head = elem;
}

int main()
{
   int x;
   struct linked_list *p;
   do
   {
       printf("Enter Number : ");
       scanf("%d",&x);
       add_element(x)
       printf("Press 'q' or 'Q' to quit or any other key to continue : ");
       scanf("%c",&c);
   }while(c!='q' && c!='Q');

   for (p=head;p!=NULL;p=p->next)
   {
        printf(%d\r\n",p->x);
   }

}
MOHAMED
  • 41,599
  • 58
  • 163
  • 268