Sunday, July 12, 2009

How to create a word using a pointer to some dynamic memory in c++?

"we will not assume anything about the maximum length word that might be processed. So, a word will not be an array of some constant size, but rather a pointer to some dynamic memory where the word is stored. "





The only way I know how to make a word is through char arrays. How exactly can i do it the other way?

How to create a word using a pointer to some dynamic memory in c++?
There are specialized string classes in most C++ variants today, but this sounds like it's talking more about the old C memory allocation functions: malloc and calloc, and their cohort free.





In general, you have to determine how much memory to allocate (how big the word is, plus one character for the null byte string terminator), then use malloc or calloc to give you a chunk of memory that big. Usually, you'll have read the word in as a part of a string, say a line of keyboard input, and are splitting the whole string up into pieces.





In general, the code will look something like this:





char* pWord = NULL;


// Now read in the line and cycle through it looking for word separators. For each word, do the following:





pWord = calloc( size_of_word, sizeof( char )); // calloc clears the memory to zero -- a handy side effect


strncpy( pWord, point_in_line_where_word_starts, number_of_chars_in_word )





When you're done using the word(s), you call free to return the space to the system.





Hope that helps.
Reply:try this


char *pWord;


then make a work


char i = 'Hello';


*pWord = i;





Why not make a *pWord a Free Store memory;





like this


char i = 'Hello';


char *pWord = new char;


then u can asign it to any word u want like this.


*pWord = i;


If you want to asign it to different value u can


delete pWord;


*pWord = new char;


then again it.





I think this is right.

surveys

No comments:

Post a Comment