Sizeof doesn't return the true size of variable in C

后端 未结 8 1126
醉梦人生
醉梦人生 2020-12-22 10:47

Consider the following code

#include 

void print(char string[]){
 printf(\"%s:%d\\n\",string,sizeof(string));
}

int main(){
 char string[] =         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-22 11:04

    A string in c is just an array of characters. It isn't necessarily NUL terminated (although in your case it is). There is no way for the function to know how long the string is that's passed to it - it's just given the address of the string as a pointer.

    "String" is that pointer and on your machine (a 32 bit machine) it takes 4 bytes to store a pointer. So sizeof(string) is 4

提交回复
热议问题