web analytics

char [] vs. char* in C++

Options

davegate 143 - 921
@2015-12-23 10:18:47

The following code snippest shows you how to initialize a char array variable and a char pointer variable in C++:

char boy[] = "Danny"; 
...
... 
char *p_son;
p_son = new char[ strlen( boy ) + 1 ]; 
strcpy( p_son, boy ); 

... 

if ( !strcmp( p_son, boy )) 
   take_to_disneyland( boy );
@2015-12-23 10:47:28

Please note, the function call strlen will return the number of character before null terminator(\0), in order to allocate enough space to hold the value of char array, you have to initialize the char pointer variable as shown above, otherwise you will have memory problem.

p_son = new char[ strlen( boy ) + 1 ];

 

 

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com