Print elements of an array in C ++

0

I am trying to print the elements of the fruit array inside a for , but the code is not working. Where am I going wrong?

int main()
{
    char frutas[20][4] = {
                            "Açaí",
                            "Acerola",
                            "Abacate",
                            "Abacaxi",
                            "Ameixa"
                         };

    int size_elements = sizeof(frutas[0]);
    int i;

    printf("Total Elementos Matriz: %d\n", size_elements);

    for(i = 0; i<size_elements; i++){
        printf("%c\n", frutas[i]);
    }

    system("pause");
    return 0;
}
    
asked by anonymous 04.02.2018 / 18:07

1 answer

0

The size set for the frutas array is not correct:

char frutas[20][4]

First you specified 4 when you have 5 fruits. And for that it is inverted and should be:

char frutas[5][20]

It is worth mentioning that it is an array of strings soon first comes the amount of strings and only then the size of each.

Given this difference, the% w / w% of the size you have to calculate the size is also not valid:

int size_elements = sizeof(frutas[0]);

Instead you can now pick up the whole array size and divide by the amount of letters they all have:

int size_elements = sizeof(frutas)/20;

Finally, if you want to sizeof show strings then you should use for .

See the code with these changes:

int main()
{
    char frutas[5][20] = {
    /*----------^---^ */    "Açaí",
                            "Acerola",
                            "Abacate",
                            "Abacaxi",
                            "Ameixa"
                         };

    int size_elements = sizeof(frutas)/20; //<-- divide por o tamanho de todas as strings
    int i;

    printf("Total Elementos Matriz: %d\n", size_elements);

    for(i = 0; i< size_elements /*<--agora size elements*/; i++){
        printf("%s\n", frutas[i]);
        //-------^ agora %s
    }

    return 0;
}

See also working on Ideone

    
04.02.2018 / 19:22