首页 > 解决方案 > 在c中使用循环打印字符串的所有方法是什么

问题描述

char testArray[][50] = {"Mango", "Strawberry", "Bannana", "Cherry"};

for(int x = 0; x<testArray; x++){
    printf("%s", testArray[x]);
}


我正在尝试找到可以使用 c 语言循环打印字符串的所有方法。任何帮助将非常感激。谢谢你。

标签: arrayscstringloops

解决方案


for 循环中的条件不正确。将整数与指针进行比较。

for(int x = 0; x<testArray; x++){
               ^^^^^^^^^^^

printf由于使用了不正确的转换说明符来输出字符串,因此调用 调用未定义的行为。

printf("%c", testArray[x]);
       ^^^^ 

你可以写

char testArray[][50] = {"Mango", "Strawberry", "Bannana", "Cherry"};
const size_t N = sizeof( testArray ) / sizeof( *testArray );

for ( size_t i = 0; i < N; i++ )
{
    printf( "%s\n", testArray[i] ); // or just puts( testArray[i] );
}

推荐阅读