Difference between using character pointers and character arrays

前端 未结 9 1124
不思量自难忘°
不思量自难忘° 2020-11-29 03:45

Basic question.

char new_str[]=\"\";

char * newstr;

If I have to concatenate some data into it or use string functions like strcat/substr/

9条回答
  •  借酒劲吻你
    2020-11-29 04:09

    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";
    

提交回复
热议问题