Is there a way to allocate memory, where you can increase the size, without losing information?
-
I'm doing a project where i have to keep reading a struct from the disk and i have to keep doing this until i come to a special set of bits. I don't know how many structs are on the disk so i need to be able to do something like this:
unsigned int num_structs = 0;
struct_name *the_struct;do
{
num_structs++;
the_struct = realloc(sizeof(the_struct)*num_structs);
read_struct(&the_struct[num_structs-1]);
} while (nextbits() == 'whatever')Where the function
realloc
will preserve the data already written in the memory area. Is this possible? thanks! -
I'm doing a project where i have to keep reading a struct from the disk and i have to keep doing this until i come to a special set of bits. I don't know how many structs are on the disk so i need to be able to do something like this:
unsigned int num_structs = 0;
struct_name *the_struct;do
{
num_structs++;
the_struct = realloc(sizeof(the_struct)*num_structs);
read_struct(&the_struct[num_structs-1]);
} while (nextbits() == 'whatever')Where the function
realloc
will preserve the data already written in the memory area. Is this possible? thanks!No. But you can do this: unsigned int size; int* array; for( int i = 0;i < 10;i++ ) { int* temp = array; size++; array = new int[size]; memcpy( array, temp, sizeof(int) * (size-1) ); delete[] temp; }
-
I'm doing a project where i have to keep reading a struct from the disk and i have to keep doing this until i come to a special set of bits. I don't know how many structs are on the disk so i need to be able to do something like this:
unsigned int num_structs = 0;
struct_name *the_struct;do
{
num_structs++;
the_struct = realloc(sizeof(the_struct)*num_structs);
read_struct(&the_struct[num_structs-1]);
} while (nextbits() == 'whatever')Where the function
realloc
will preserve the data already written in the memory area. Is this possible? thanks!have a look on std::vector http://www.msoe.edu/eecs/ce/courseinfo/stl/vector.htm