What does that mean in c? char *array[]= { “**”, “**”, “**” };

后端 未结 5 477
花落未央
花落未央 2021-01-13 10:45

In some code that I read, there was an initializing statement like this

char *array[]= { \"something1\", \"something2\", \"something3\" };

5条回答
  •  情歌与酒
    2021-01-13 11:33

    char * in C is a string.

    array is the name of the variable being declared.

    [] indicates that it is an array.

    { "something1", "something2", "something3" } is initializing the contents of the array.

    Accessing elements is done like so:

    array[0] gives the 1st element - "something1".

    array[1] gives the 2nd element - "something2".

    etc.

    Note:

    As was pointed out in the comments, char * isn't technically a string.

    It's a pointer to a char. You can visualize a string in memory like so:

    <-------------------------->
    ..134|135|136|137|138|139|..
    <-------------------------->
      'H'|'e'|'l'|'l'|'o'|'\0'
    <-------------------------->
    

    This block of memory (locations 134-139) is holding the string of characters.

    For example:

    array[0] actually returns a pointer to the first character in "something1".

    You use the fact that the characters are sequentially in memory to access the rest of the string in various ways:

    /* ch points to the 's' */
    char* ch = array[0];
    
    /* ch2 points to the 'e' */
    char* ch2 = ch + 3;
    
    /* ch3 == 'e' */
    char ch3 = *ch2;
    
    /* ch4 == 'e' */
    char ch4 = *(ch + 3);
    
    /* ch5 == 'e' */
    char ch5 = ch[3];
    

提交回复
热议问题