Pergunta

I'm working with some arrays in plain C99 and I need to know their size. Does anyone knows why this is happening:

int function(char* m){
    return sizeof(m) / sizeof(m[0]);
}

int main(){
    char p[100];
    int s = sizeof(p) / sizeof(p[0]);
    printf("Size main: %d\nSize function: %d\n",s,function(p));
    return 0;
}

Output:

Size main: 100
Size function: 8

Thanks!

Foi útil?

Solução

Arrays decay to pointers at the first chance they get, thus in function all you have is a pointer, which is 8 bytes in your case.

Outras dicas

This is happening because sizeof(m) == sizeof(char*), which is 8 on your platform.

When you call function(p), p decays into a pointer and loses its size information.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top