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 .