Difference between using character pointers and character arrays

Viewed 23623

Basic question.

char new_str[]="";

char * newstr;

If I have to concatenate some data into it or use string functions like strcat/substr/strcpy, what's the difference between the two?

I understand I have to allocate memory to the char * approach (Line #2). I'm not really sure how though.

And const char * and string literals are the same?

I need to know more on this. Can someone point to some nice exhaustive content/material?

9 Answers

To differentiate them in the memory allocation side:

// With char array, "hello" is allocated on stack
char s[] = "hello";

// With char pointer, "hello" is stored in the read-only data segment in C++'s memory layout.
char *s = "hello";

// To allocate a string on heap, malloc 6 bytes, due to a NUL byte in the end
char *s = malloc(6);
s = "hello";
Related