How to define array which size is do not know yet

I have a txt file of double variable. Total record is given different each time.

How to define array which i do not know the size until the reading file record then i only can know the size of the array
Try the following code:
int len;
int *array=new int[len];

Replace all int's with the appropriate type of array you want and replace cin with your length calculation of your file record.
Last edited on
is the same way in c also coz i using c language..
Excuse me? I didn't get your last statement.
Did it work?
Did you try it maggie? Otherwise you can always use realloc that is the c version of new operator / operator new in c++.
If you've not lean't about using pointers for dynamic memory yet and about the heap memory then I suggest you do so!

Just make sure that you keep hold of the pointer value under array and make sure you delete it once you're finished with your data.

int size;
std::cin >> size;
int* array = new int[size];
//Do stuff with my data here

delete array;
//This frees the memory back to the system

array = NULL;
This sets array to 0 instead of the position where the data used to be
(freed with delete), this is to prevent you accidentally accessing
unpredictable data sources.

@giblit.. I thought it was (typename)malloc(size) for the C compatible version... Anyways you have again forgot to mention that this must return memory back to the system when it's finished with free(ptr)
Last edited on
I wasn't telling him how to do it I was just mentioning a way. Also your code has a memory leak line 6 should be delete[] array; Remember when you use new[] operator you must use delete[] operator.
is the same way in c also coz i using c language..

If you're writing in C, and not C++, then you'll need to use malloc and free. As SatsumaBenji said, you should learn about pointers, and about dynamic memory allocation.
Erm, yeah...
I was testing you XD

I was wondering if someone would spot that error =P
Topic archived. No new replies allowed.