C strings confusion

前端 未结 7 2178
深忆病人
深忆病人 2020-11-27 14:30

I\'m learning C right now and got a bit confused with character arrays - strings.

char name[15]=\"Fortran\";

No problem with this - its an

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 14:53

    It is confusing indeed. The important thing to understand and distinguish is that char name[] declares array and char* name declares pointer. The two are different animals.

    However, array in C can be implicitly converted to pointer to its first element. This gives you ability to perform pointer arithmetic and iterate through array elements (it does not matter elements of what type, char or not). As @which mentioned, you can use both, indexing operator or pointer arithmetic to access array elements. In fact, indexing operator is just a syntactic sugar (another representation of the same expression) for pointer arithmetic.

    It is important to distinguish difference between array and pointer to first element of array. It is possible to query size of array declared as char name[15] using sizeof operator:

    char name[15] = { 0 };
    size_t s = sizeof(name);
    assert(s == 15);
    

    but if you apply sizeof to char* name you will get size of pointer on your platform (i.e. 4 bytes):

    char* name = 0;
    size_t s = sizeof(name);
    assert(s == 4); // assuming pointer is 4-bytes long on your compiler/machine
    

    Also, the two forms of definitions of arrays of char elements are equivalent:

    char letters1[5] = { 'a', 'b', 'c', 'd', '\0' };
    char letters2[5] = "abcd"; /* 5th element implicitly gets value of 0 */
    

    The dual nature of arrays, the implicit conversion of array to pointer to its first element, in C (and also C++) language, pointer can be used as iterator to walk through array elements:

    / *skip to 'd' letter */
    char* it = letters1;
    for (int i = 0; i < 3; i++)
        it++;
    

提交回复
热议问题