2D character array initialization in C

前端 未结 4 1473
臣服心动
臣服心动 2021-02-03 10:23

I am trying to build a list of strings that I need to pass to a function expecting char **

How do I build this array? I want to pass in two options, each wi

4条回答
  •  执念已碎
    2021-02-03 10:42

    How to create an array size 5 containing pointers to characters:

    char *array_of_pointers[ 5 ];        //array size 5 containing pointers to char
    char m = 'm';                        //character value holding the value 'm'
    array_of_pointers[0] = &m;           //assign m ptr into the array position 0.
    printf("%c", *array_of_pointers[0]); //get the value of the pointer to m
    

    How to create a pointer to an array of characters:

    char (*pointer_to_array)[ 5 ];        //A pointer to an array containing 5 chars
    char m = 'm';                         //character value holding the value 'm'
    *pointer_to_array[0] = m;             //dereference array and put m in position 0
    printf("%c", (*pointer_to_array)[0]); //dereference array and get position 0
    

    How to create an 2D array containing pointers to characters:

    char *array_of_pointers[5][2];          
    //An array size 5 containing arrays size 2 containing pointers to char
    
    char m = 'm';                           
    //character value holding the value 'm'
    
    array_of_pointers[4][1] = &m;           
    //Get position 4 of array, then get position 1, then put m ptr in there.
    
    printf("%c", *array_of_pointers[4][1]); 
    //Get position 4 of array, then get position 1 and dereference it.
    

    How to create a pointer to an 2D array of characters:

    char (*pointer_to_array)[5][2];
    //A pointer to an array size 5 each containing arrays size 2 which hold chars
    
    char m = 'm';                            
    //character value holding the value 'm'
    
    (*pointer_to_array)[4][1] = m;           
    //dereference array, Get position 4, get position 1, put m there.
    
    printf("%c", (*pointer_to_array)[4][1]); 
    //dereference array, Get position 4, get position 1
    

    To help you out with understanding how humans should read complex C/C++ declarations read this: http://www.programmerinterview.com/index.php/c-cplusplus/c-declarations/

提交回复
热议问题