Jezzie
Jezzie

Reputation: 39

Printing array of strings character by character

I am not very familiar with C yet and faced yet another problem. Usually I found answers to my problems from here but this time I didn't. Probably there is a one but anyways...

Here is the deal. I have an array of strings and I want to print them, each item one their own line. Array ends with NULL.

Here is a simplified version of the code I have atm.

print_my_array(char *array[])
{ 

    while(*array != NULL){
        char *item = *array;
        while (item)
        {
            int i = 0;
            printf("%c", item[i]);
            i++;
        }
        printf("\n");
        array++;
    }

}

So this is what I believe my code does. I have the array called array. I take the pointer called item and point the first item in array with it. Then I loop over the item and print all the chars one by one. When I have gone through the item I print \n and move to the next item by moving the array pointer and beginning the loop all over.

Upvotes: 1

Views: 70

Answers (2)

Cristinadeveloper
Cristinadeveloper

Reputation: 93

I did an example function, where you loop inside the array with a position until it gets a null value. Later, you see if you printed some character or not, and it tells you if the array was void:

 exampleFunction(char array[]){
        int position = 0;

        while(array[position]) {
            printf("%c\n", array[position]);
            position++;
        }

        if(position == 0){
            printf("The array was void.");
        }
}

I didn't use pointers, but I think it works anyway. I hope this helps!

Upvotes: 0

unwind
unwind

Reputation: 400129

The inner loop is wrong:

while (item)
{
  // all your code
}

should be

while (*item)
{
  printf("%c", *item++);
}

But of course, it'd make way more sense to use printf("%s\n", *array++); and skip the inner loop altogether.

Upvotes: 3

Related Questions