C++ function returning pointer, why does this work ? [migrated]
- by nashmaniac
So heres a simple c++ function what it does it take an array of characters as its argument and a integer n and then creates a new character array with only n elements of the array.
char * cutString(char * ch , int n){
char * p = new char[n];
int i ;
for(i = 0 ; i < n ; i++)
p[i] = ch[i];
while(i <= n ){
p[i++] = '\0';
}
return p ;
}
this works just fine but if I change
char * p = new char[n]; to char p[n];
I see funny characters what happens ? What difference does the former make
also p is a temporary variable then how does the function returns it alright ?