Print matrix elements in C++

Asked

Viewed 619 times

0

I’m trying to print the elements of the fruit matrix inside a for, but the code is not working. Where I am missing?

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

1 answer

0


The size set for the matrix frutas is not correct:

char frutas[20][4]

First specified 4 when you have 5 fruit. And besides it is inverted and should be:

char frutas[5][20]

Remember that it is an array of strings then first comes the number of strings and only then the size of each one.

Taking into account this difference the sizeof that has to calculate the size is also not valid:

int size_elements = sizeof(frutas[0]);

Instead you can now take the size of the whole matrix and divide by the amount of letters that they all have:

int size_elements = sizeof(frutas)/20;

Finally it is intended in the for show strings so you should use %s.

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

  • Thanks Isac. It’s perfect!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.