Ok, there is no problem in initializing the pointer. The problem is that this pointer points to NULL. Your pointer needs to point to a valid area in the memory.
For example:
1 2
|
char *s=NULL;
*s = 'z'; // write z to the point where s points. Where does s point?
| |
This code will crash, because you are trying to write to the NULL location.
There are two simple alternatives, either you allocate a memory area statically by creating an array, or dynamically reserving a memory area with
new operator.
When you define an array with a size,
char mystring [100],that means you are creating a pointer of char type with the name mystring and this pointer points to the start of a memory area of 100 chars. That way the compiler knows what to do.
Or you can either use the new operator as such:
1 2
|
char * s;
s = new char [50];
| |
Here you have the valid pointer which points to the start of an allocated area with 50 char size.
You can read the tutorial for dynamic memory allocation:
http://www.cplusplus.com/doc/tutorial/dynamic/