How would I make an array to store strings?

前端 未结 4 1558
暖寄归人
暖寄归人 2021-01-29 11:22

So I\'m trying to figure this out with a simple program:

#include 
#include 
#include 
 int main()
{
    char a[]=         


        
4条回答
  •  日久生厌
    2021-01-29 11:38

    The declaration char a[] = "lalala"; creates an array of characters, where the name a is an alias for the memory address where the first character is stored.

    To create an array of strings, you can make an array of character pointers, each of which holds the memory address of the starting position of a single character array.

    #include 
    
    int main(void)
    {
    
        /* Store the starting address of each character array in an array of
         * character pointers */
    
        char alpha[] = "Alpha";  /* Array of characters */
        char beta[] = "Beta";
        char gamma[] = "Gamma";
    
        char *char_ptr_array[3]; /* Array of pointers to characters */
    
        char_ptr_array[0] = &alpha[0]; 
        char_ptr_array[1] = beta; 
            /* This does the same thing since the array's name is an alias
             * for the address of the first element */
        char_ptr_array[2] = gamma;
    
        printf("%s, %s, %s\n", char_ptr_array[0], char_ptr_array[1], char_ptr_array[2]);
    
        return(0);
    }
    

    You can also make the assignment like this, which is a shorthand for doing the same thing:

    #include 
    
    int main (void)
    {
        char *alphabet[3] = { "Alpha", "Beta", "Gamma" };
    
        printf("%s, %s, %s\n", alphabet[0], alphabet[1], alphabet[2]);
    
        return(0);
    }
    

提交回复
热议问题