Hello 2 questions, when you've got this:

char * array = new char[20];

creates a dynamic array of 20, if on run time the array needs to be 40 how could this be accomplished? I've thought i'd fill the array and if the next element that requires adding goes out of boundsn create a new array and copy the data over? Fair enough this is a big overhead in terms of time access.

Also if you have an array like this:

char * array = new char[20];
array = "World";

this create an dynamic array of 20 bytes and populates it with "World" , however if i then go away and want to add something to the beginning of the array, ie

"Hello"

How could this be accomplished? Via making and copy the data to a new array?

strcpy if im correct 'copies' the data from array[0]?

Thanks guys,

John

>creates a dynamic array of 20
"Simulates" an array of 20.

>if on run time the array needs to be 40 how could this be accomplished?
Allocate a new block with the new size.
Copy the contents of the old block.
Free the memory of the old block.

C++ doesn't have the equivalent of realloc, but the worst case effect of realloc is basically the same as above.

>this create an dynamic array of 20 bytes and populates it with "World"
No, it allocates 20 bytes and promptly leaks them away when you point the pointer to the address of a string literal.

>however if i then go away and want to add something to the beginning of the array
Assuming you're doing it correctly instead of what you were doing, you would shift the contents of the array to make a hole where you can then copy the new string. This prepends the string you have, but it's rather expensive.

>strcpy if im correct 'copies' the data from array[0]?
Yes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.