There are 3 things to remember when using pointers with a string. The main thing is that your pointer needs to have a block of memory assigned to it - otherwise, your string will be stored at a random memory location and could easily damage some other data.
The second thing is that this block of memory needs to be big enough to hold the string PLUS an extra byte for a NULL terminator (you might need a couple of extra bytes if you're using Unicode or some other multi-byte character string). So - what happens if you don't know how big the string will be? Just allocate a big enough block to hold the maximum size you think it will probably be and hope for the best....!
The final thing to remember is that every block of allocated memory must be released once you've finished with it.
In C, memory is allocated using 'malloc()' and released using 'free()'. In C++ it is allocated using the 'new' operator and released using 'delete[]'. Note the square brackets. Here's an example in C assuming a simple character string......
Code:
#define MAX_STRING_SIZE 1024;
char* pStringBuffer = NULL;
pStringBuffer = (char *)malloc(MAX_STRING_SIZE);
/* 'malloc()' returns a pointer to void, so cast it as a pointer to char */
if (pStringBuffer)
{
strcpy (pStringBuffer, "Hello World");
/* Now do something with the string */
/* and finally... */
free (pStringBuffer);
}
And the same thing in C++......
Code:
#define MAX_STRING_SIZE 1024;
char* pStringBuffer = NULL;
pStringBuffer = new char[MAX_STRING_SIZE]; // Note the square brackets
if (pStringBuffer)
{
strcpy (pStringBuffer, "Hello World");
// Now do something with the string
// and finally...
delete[] pStringBuffer; // Note the square brackets again
}
Strictly speaking, the 'if' test is dangerous under C++ because unlike malloc(), 'new' is not guaranteed to return NULL if it fails. However, I've never come across a compiler where it didn't.
Incidentally, for most purposes it's easier to hold strings on the program stack. This is especially true if they're small and only being used temporarily - e.g.
Code:
char stringBuffer[] = "Hello World";
This automatically allocates the right amount of space and the memory doesn't need to be released afterwards. The drawback is that you need to make sure that you don't accidentally overwrite stringBuffer with a bigger string.
Hope that helps.