Problems with sizeof

Asked

Viewed 225 times

7

I’m trying to get back the size of array, but it’s making a mistake. What to do?

#include <stdio.h>
char *palavra[] = {"casa", "carro"};
int main(){
    int i;
    for(i = 0;i < sizeof(palavra);i++){ //Segmentation fault aqui.
        printf(palavra[i]);
    }
    return 0;
}

2 answers

7


The error is not on this line, it is on the bottom, when you will access the element. Access the element 0 and is ok, access the element 1 and is ok, when will access the 3 gives the error. Why are you trying to access 3? Why the error in the wrong calculation of sizeof.

The sizeof takes the size of the whole array, all memory space. In this case the array is pointer type, and in architecture 32 bits has size 4 bytes. As are two elements, the array has size 8. What you want is size 2. So you have to split the size of the array by the size of the element, thus giving the expected result. 8 which is the total size, divided by 4 which is the size of the pointer, gives 2, which is the correct result.

#include <stdio.h>
int main() {
    char *palavra[] = {"casa", "carro"};
    for (int i = 0; i < sizeof(palavra) / sizeof(palavra[0]); i++) printf("%s", palavra[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I tried to use this mode you proposed but the compiler still returns.

  • @Thiagomartendal you clicked us links that I put in the answer? There it shows in two different compilers that it works. You must be doing something else. Put your code on ideone and show error.

  • ready I got.

  • 1

    +1. But: "[...] when you go to access 3 gives the error.". Wouldn’t "2" be? (i.e. indexing from 0 to 1 for 2 items in the array)

6

sizeof returns the size of the memory allocated by the pointer, not the number of elements.

To go through this for Voce you need to know the number of array elements and use this value as a stop condition

#include <stdio.h>
char *palavra[] = {"casa", "carro"};
int tamanho = 2;
int main(){
    int i;
    for(i = 0; i < tamanho; i++){
        printf(palavra[i]);
    }
    return 0;
}

Browser other questions tagged

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