By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,188 Members | 832 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,188 IT Pros & Developers. It's quick & easy.

How to create dynamic char array?

100+
P: 151
I am working on dynamic array which grows with input data size. Its size may grow from 30 to 30000000 character. I don't want to initialize an array of size 30000000. Like

char* array = new char[30000001];

How can i do it dynamically? Thanks in advance.
Dec 1 '10 #1
Share this Question
Share on Google+
7 Replies


Banfa
Expert Mod 5K+
P: 8,916
Don't use arrays use a vector!

Anyway what you have given as what you don't want to do is the dynamic way to do things, your question is not clear.
Dec 1 '10 #2

100+
P: 151
Thanks

vector solve the pblm but i don't want to use STL.It will slow down the performance.
Dec 1 '10 #3

Banfa
Expert Mod 5K+
P: 8,916
It is very unlikely that a vector will slow down performance since under optimisation it is as efficient as a normal array.
Dec 1 '10 #4

100+
P: 151
Thanks for reply. As per my project demand i am not supposed to use stl and string class. Below is an example of my need.


#include <iostream>
using namespace std;
int main()
{
char str1[20] = "0000000000000000000";
char str2[10] = "000000000";

// insert str2 into str1 at position 5 in str1
return 0;
}
How this can be done? Since this needs size of str1 to be 30 which is now 20. How it can be increased. It is possible in string easily. But i want to use char*.

Thanks again for your reply.
Dec 1 '10 #5

100+
P: 207
Can you use the CString standard header for your project? It provides a lot of useful functions when working with old school strings.

Here is a reference...
http://www.cplusplus.com/reference/clibrary/cstring/
Dec 1 '10 #6

Expert 100+
P: 2,398
The way to do this in C is to use realloc each time you need to increase the size of the string. The copy implicit to realloc can be handy, but it may be more efficient to use malloc and an explicit copy if your string typically grows because you insert a substring into the middle of it. Likewise, it might be substantially more efficient to always request more memory than you need to reduce the number of allocation calls.

However, C++ programs tend to be more elegant than brute-force C. <wink>
Dec 1 '10 #7

Oralloy
Expert 100+
P: 983
Man4ish,

Is this a school project?

If so, please take a cut at writing the answer, then ask specific questions about details. Anything more is way out of bounds from an academic integrity standpoint.

Cheers!
Oralloy
Dec 1 '10 #8

Post your reply

Sign in to post your reply or Sign up for a free account.