char testArray[][50] = {"Mango", "Strawberry", "Bannana", "Cherry"};
for(int x = 0; x<testArray; x ){
printf("%s", testArray[x]);
}
I am trying to find all the ways I can print strings using loops in c language. Any help would be much appreciated. Thank you.
CodePudding user response:
The condition in your for loop is incorrect. There are compared an integer with a pointer.
for(int x = 0; x<testArray; x ){
^^^^^^^^^^^
Also the call of printf
invokes undefined behavior because there is used an incorrect conversion specifier to output a string.
printf("%c", testArray[x]);
^^^^
You could write
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] );
}
CodePudding user response:
if you want pointers:
#define TSIZE(x) (sizeof(x) / sizeof((x)[0]))
int main(void) {
char testArray[][50] = {"Mango", "Strawberry", "Bannana", "Cherry"};
for(char (*x)[50] = testArray; x < &testArray[TSIZE(testArray)]; x ){
printf("%s\n", *x);
}
}
or of you want to use %c
format:
int main(void) {
char testArray[][50] = {"Mango", "Strawberry", "Bannana", "Cherry"};
for(char (*x)[50] = testArray; x < &testArray[TSIZE(testArray)]; x )
{
char *p = x[0];
while(*p)
printf("%c", *p );
printf("\n");
}
}