How would I make an array to store strings?

前端 未结 4 1554
暖寄归人
暖寄归人 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:25

    Try using strcpy instead of assigning them by dereferencing.

    0 讨论(0)
  • 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 <stdio.h>
    
    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 <stdio.h>
    
    int main (void)
    {
        char *alphabet[3] = { "Alpha", "Beta", "Gamma" };
    
        printf("%s, %s, %s\n", alphabet[0], alphabet[1], alphabet[2]);
    
        return(0);
    }
    
    0 讨论(0)
  • 2021-01-29 11:43

    You could use an array of strings:

    std::string test[20];
    

    And avoid using #include <string.h>; use just #include <string>.

    0 讨论(0)
  • 2021-01-29 11:45

    To store entire string use string copy.

    char a[]="lalala"; 
    char c[]="nanana";
    char d[3][10];
    
    strcpy(d[0],a);
    strcpy(d[1],b);
    strcpy(d[2],c);
    
    printf("%s -- %s -- %s", d[0], d[1], d[2]);
    
    0 讨论(0)
提交回复
热议问题