C strings confusion

前端 未结 7 2176
深忆病人
深忆病人 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 15:00

    In C a string is actually just an array of characters, as you can see by the definition. However, superficially, any array is just a pointer to its first element, see below for the subtle intricacies. There is no range checking in C, the range you supply in the variable declaration has only meaning for the memory allocation for the variable.

    a[x] is the same as *(a + x), i.e. dereference of the pointer a incremented by x.

    if you used the following:

    char foo[] = "foobar";
    char bar = *foo;
    

    bar will be set to 'f'

    To stave of confusion and avoid misleading people, some extra words on the more intricate difference between pointers and arrays, thanks avakar:

    In some cases a pointer is actually semantically different from an array, a (non-exhaustive) list of examples:

    //sizeof
    sizeof(char*) != sizeof(char[10])
    
    //lvalues
    char foo[] = "foobar";
    char bar[] = "baz";
    char* p;
    foo = bar; // compile error, array is not an lvalue
    p = bar; //just fine p now points to the array contents of bar
    
    // multidimensional arrays
    int baz[2][2];
    int* q = baz; //compile error, multidimensional arrays can not decay into pointer
    int* r = baz[0]; //just fine, r now points to the first element of the first "row" of baz
    int x = baz[1][1];
    int y = r[1][1]; //compile error, don't know dimensions of array, so subscripting is not possible
    int z = r[1]: //just fine, z now holds the second element of the first "row" of baz
    

    And finally a fun bit of trivia; since a[x] is equivalent to *(a + x) you can actually use e.g. '3[a]' to access the fourth element of array a. I.e. the following is perfectly legal code, and will print 'b' the fourth character of string foo.

    #include 
    
    int main(int argc, char** argv) {
      char foo[] = "foobar";
    
      printf("%c\n", 3[foo]);
    
      return 0;
    }
    

提交回复
热议问题