如何在C中打印未大小的数组

时间:2016-02-16 17:41:25

标签: c multidimensional-array printf

我是C的新手并试图弄清楚如何在C中打印未经过大小处理的数组。使用下面的代码,我看起来很怪异,但我无法弄清楚原因。

我需要一些帮助:

main()
{
    int i;
    char *prt_1st;
    char list_ch[][2] = {'1','a', '2','b', '3','c','4','d','5','e','6','f' };

    prt_1st = list_ch;
    for (i = 0; i < sizeof(list_ch); i++) {
        prt_1st +=  i;
        printf("The content of the array is %c under %d position\n", *prt_1st, i);
    }
}

4 个答案:

答案 0 :(得分:2)

好的,代码中的问题是,在以下行中

prt_1st +=  i;

它会将指针递增i次,但您需要的是将它递增1。

这是修改后的代码

int main()
{
    int i;
    char *prt_1st;
    char list_ch[][2] = {'1','a', '2','b', '3','c','4','d','5','e','6','f' };

    prt_1st = list_ch[0];

    for (i = 0; i < sizeof(list_ch); i++) 
    {
        //prt_1st +=  i;    
        printf("The content of the array is %c under %d position\n", *prt_1st, i);
        prt_1st =  prt_1st + 1;
    }
    return 0;
}

答案 1 :(得分:1)

可以通过获取元素数来打印未定义长度的数组

  • 元素总大小
  • 元素的个别大小

    在这种情况下

    
        sizeof(list_ch) returns Total array size.
        sizeof(char) returns an individual character size.
    
    therefore,
        Total number of elements (n) = sizeof(list_ch)/sizeof(char)
    
    
    iterate the array using
    
    
    iterate a for loop 
        // Either format your code using ptr format
        *(list_ch+i); 
        // or a 1D Array 
        list_ch[i]; 
    

    或者您只需使用增量解决方案

     
    
    printf("%s", list_ch)
    ++list_ch 
    
    
    
    This will automatically put your ptr to the next index in your array
    

    希望这会有所帮助:)

  • 答案 2 :(得分:1)

    以下工作和处理可能的对齐问题:

    int main()
    {
        int i, j;
        char (*prt_1st)[2];
        char list_ch[][2] = {{'1','a'}, {'2','b'}, {'3','c'},{'4','d'},{'5','e'},{'6','f'} };
    
        for (i = 0; i < sizeof(list_ch)/sizeof(list_ch[2]); i++) {
            for (j=0; j<sizeof(list_ch[2]); j++)
                printf("The content of the array is %c under %d,%d position\n", list_ch[i][j], i,j);
        }
        return(0);
    }
    

    答案 3 :(得分:1)

    您应该以这种方式声明并初始化第一个未指定大小的二维数组:

    char list_ch[][2] = {{'1','a'}, {'2','b'}, {'3','c'}, {'4','d'}, {'5','e'}, {'6','f'}};
    

    这样做sizeof(list_ch)的结果为12。数组的元素应该在内存中是连续的(除非@ PualOgilvie 指出,编译器决定让每一行从一个字边界开始,导致一个解除分配),你可以在循环中扫描它们像这样的指针:

    int i;
    char *prt_1st = list_ch;
    for (i = 0; i < sizeof(list_ch); i++) {
        printf("Position: %d Element: %c\n", i, prt_1st[i]);
    }
    

    或保持2D性质:

    char *prt_1st;
    int dim = sizeof(list_ch) / sizeof(list_ch[0]);
    for (i = 0; i < dim; i++) {
        prt_1st = list_ch[i];
        printf("The first char of row %d is %c\n", i, prt_1st[0]);
    }