Problems with sizeof

6

I am trying to return the size of the array , but it is giving error. 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;
}
    
asked by anonymous 19.01.2017 / 16:02

2 answers

7

The error is not in this line, it is in the bottom, when it will access the element. Access element 0 and it is ok, access element 1 and it is ok, when going to 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 entire array , all space occupied in memory. In case the array is of type pointer, and in architecture 32 bits has the size 4 bytes. Since they are two elements, the array has size 8. What you want is size 2. So you have to divide the array by the size of the element, 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(palavra[i]);
    }
}

See running on ideone . And at Coding Ground . Also I put it in GitHub for future reference .

    
19.01.2017 / 16:11
5

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

To go through this, you need to know the number of elements in the array and use this value as the 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;
}
    
19.01.2017 / 16:10