Difference between char* and char[]

前端 未结 7 1240
清歌不尽
清歌不尽 2020-11-27 03:32

I know this is a very basic question. I am confused as to why and how are the following different.

char str[] = \"Test\";
char *str = \"Test\";
7条回答
  •  轮回少年
    2020-11-27 03:36

    "Test" is an array of five characters (4 letters, plus the null terminator.

    char str1[] = "Test"; creates that array of 5 characters, and names it str1. You can modify the contents of that array as much as you like, e.g. str1[0] = 'B';

    char *str2 = "Test"; creates that array of 5 characters, doesn't name it, and also creates a pointer named str2. It sets str2 to point at that array of 5 characters. You can follow the pointer to modify the array as much as you like, e.g. str2[0] = 'B'; or *str2 = 'B';. You can even reassign that pointer to point someplace else, e.g. str2 = "other";.

    An array is the text in quotes. The pointer merely points at it. You can do a lot of similar things with each, but they are different:

    char str_arr[] = "Test";
    char *strp = "Test";
    
    // modify
    str_arr[0] = 'B'; // ok, str_arr is now "Best"
    strp[0] = 'W';    // ok, strp now points at "West"
    *strp = 'L';      // ok, strp now points at "Lest"
    
    // point to another string
    char another[] = "another string";
    str_arr = another;  // compilation error.  you cannot reassign an array
    strp = another;     // ok, strp now points at "another string"
    
    // size
    std::cout << sizeof(str_arr) << '\n';  // prints 5, because str_arr is five bytes
    std::cout << sizeof(strp) << '\n';     // prints 4, because strp is a pointer
    

    for that last part, note that sizeof(strp) is going to vary based on architecture. On a 32-bit machine, it will be 4 bytes, on a 64-bit machine it will be 8 bytes.

提交回复
热议问题