c - 如何在C中打印未指定大小的数组

标签 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);
    }
}

最佳答案

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

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;
}

关于c - 如何在C中打印未指定大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439456/

相关文章:

C++ printf 问题 : How can I safely pass a char* to printf?

c - Printf 产生错误的整数

qsort() 比较二维数组

PHP - 如何修改深层嵌套的关联数组?

c - 为什么我们在C/C++中有两种库?

c - 二维数组正在截断一些字符

c - 当我将二维数组传递给函数 (tes).t 时,为什么声明 *(*(arr+1)+2) 不起作用

c - sprintf 没有内存分配

c - C 中 mkfifo() 产生的段错误

arrays - Int 变量从 void 返回后神秘地改变了值