0
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.

1
  • What you wrote doesn't work. %c requires the argument to be a char, but testArray[x] is char[50]. Commented Oct 6, 2021 at 21:49

2 Answers 2

1

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] );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man help me greatly.
0

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

1 Comment

Thanks for clarification much appreciated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.