Difference between using character pointers and character arrays

前端 未结 9 1206
不思量自难忘°
不思量自难忘° 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:01

    This is a character array:

    char  buf [1000];
    

    So, for example, this makes no sense:

    buf = &some_other_buf;
    

    This is because buf, though it has characteristics of type pointer, it is already pointing to the only place that makes sense for it.

    char *ptr;
    

    On the other hand, ptr is only a pointer, and may point somewhere. Most often, it's something like this:

    ptr = buf;              // #1:  point to the beginning of buf, same as &buf[0]
    

    or maybe this:

    ptr = malloc (1000);    // #2:  allocate heap and point to it
    

    or:

    ptr = "abcdefghijklmn"; // #3:  string constant
    

    For all of these, *ptr can be written to—except the third case where some compiling environment define string constants to be unwritable.

    *ptr++ = 'h';          // writes into #1: buf[0], #2: first byte of heap, or
                           //             #3 overwrites "a"
    strcpy (ptr, "ello");  // finishes writing hello and adds a NUL
    

提交回复
热议问题