문제

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!

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top