can someone teach me how to create a dynamic array in C/C++/VC++ Juz like what we use in VB ReDim
regards,
Printable View
can someone teach me how to create a dynamic array in C/C++/VC++ Juz like what we use in VB ReDim
regards,
Dynamic arrays must be allocated on the heap, which means you need to use pointers, new and delete[]
The pointer is used to store the position where the array is allocated, new [datatypename] allocates data and returns a pointer to it for instance
int* a= new int[3];
allocates and array of 3 integers and stores the pointer in a.
then you use a as if it was an array;
a[2]=4;
cout << a[2] << endl;
and when you're done with the array you need to delete it, because since it's not on the stack, it won't be automatically deleted either.
delete[] a;
Note that if you wish to resize the array you need to copy its contents to a temporary array, delete[] the array, reallocate the memory for it with the new size and copy the contents of the temporary array to the newly allocated memory.
is there a way I can copy a array or structure with size 50 at one go instead of loop through each element?
You could do something like:
This should work. I don't think there is a way out of looping. :(PHP Code:int* theArray = new int[50];
int* tempArray;
// fill the array with something.....
int newSize = 70;
tempArray = theArray;
theArray = new int[newSize];
for (int i = 0; i < newSize; i++)
theArray[i] = tempArray[i];
delete [] tempArray;
Found a way without looping! :)
PHP Code:#include <iostream>
using namespace std;
int main()
{
int newSize;
int curSize = 50;
int* theArray = new int[curSize];
int* tempArray;
// fill the array with something.....
newSize = 70;
tempArray = theArray;
theArray = new int[newSize];
memcpy(theArray, tempArray, curSize * sizeof(int));
newSize = curSize;
delete [] tempArray;
return 0;
}
I guess that could ;) be called without looping, but if you look at a lower level, every value has to be copied.
Does anyone know if memcpy actually faster than an element by element copy?
Destined
No, atually it's the exact same speed because what memcpy does is loop and copy.
If you want something similar to ReDim Preserve, then you could use a vector.
Code:#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Creates an array of integers (replace int with
// the type of data you want to use)
vector<int> var;
// myval = amount to resize to
var.resize(myval);
// Element = element you want to change
var[element] = 343
return 0;
}
A vector is freaking 16 bytes