Sunday, August 2, 2009

In C++, how do I get the size of an integer array that was dynamically allocated by the user?

In addition, after I determine the size, I need to expand the array to a certain length based on user input by placing 0's in FRONT of the preexisting values.


for example if the array orginally contained a[0]=4, a[1]=5, a[2]=6, a[3]=7 , the user can input a length of 7 that will make a[0]=0, a[1]=0, a[2]=0, a[3]=4, a[4]=5, a[5]=6, a[6]=7

In C++, how do I get the size of an integer array that was dynamically allocated by the user?
You can not find out the size of a dynamic array (i.e. pointer)- you need to store it in a variable somewhere. To extend the buffer create a new one and copy over the old elements. There might be cases where you actually want to do this in general however, it is a much better idea to use std::list or std::vector !





int myArraySize=100;


int* myArray= new int[myArraySize]; // create


for (int i=0; i%26lt;myArraySize; ++i) // fill it up with data


myArray[i]=i;


int* newArray= new int[myArraySize*2];


memcpy(newArray+myArraySize, myArray, myArraySize*sizeof(int) ); // copy old array into tail of new array


delete[] myArray; // get rid of previous elements


// now update pointer and size info


myArray= newArray;


myArraySize= myArraySize*2;
Reply:I would create a data structure such that values can be put in on either right or left side, and taken out by index, relative to start. Store size as a data field, and create a method for expanding the data structure. Store it in a circular manner.
Reply:I don't think this is a good idea because it would be inefficient. You should instanciate class List instead. If you still insist on array, you can do it only by defining your own class in which you have to define a veriable to keep track of length allocated. To append more elements you will have to define a new array of the size existing_length+no_of_elements_to_append... then copy previous array and inserting 0s to the rest. Can you imagine how unprofessional approach this will be?


No comments:

Post a Comment