解析sizeof, strlen, 指针以及数组作为函数参数的应用

时间:2022-04-15 05:43:35

代码如下所示:

复制代码 代码如下:


typedef struct st_test
{
 int id;
 char *pName;
 char class[10];
}Student;
void fn(Student *pStud) {
 pStud->id = 10;
 pStud->pName = "Tom Simith";
 strcpy(pStud->class, "Class 1");
 printf("sizeof(pStud) = %d /n", sizeof(pStud));     // sizeof(pStud) = 4
 printf("sizeof(pStud->id) = %d /n", sizeof(pStud->id));   // sizeof(pStud->id) = 4
 printf("id:%d/n", pStud->id);         // id:10
 printf("sizeof(pStud->pName) = %d /n", sizeof(pStud->pName)); // sizeof(pStud->pName) = 4
 printf("strlen(pStud->pName) = %d /n", strlen(pStud->pName)); // strlen(pStud->pName) = 10
 printf("Name:%s/n", pStud->pName);        // Name:Tom Simith
 printf("sizeof(pStud->class) = %d /n", sizeof(pStud->class)); // sizeof(pStud->class) = 10
 printf("strlen(pStud->class) = %d /n", strlen(pStud->class)); // strlen(pStud->class) = 7
 printf("class:%s/n", pStud->class);        // class:Class 1
}
void fnArray(char arr[]) {
 printf("arr:%s/n", arr);       // arr:Hello
 printf("sizeof(arr) = %d /n", sizeof(arr));   // sizeof(arr) = 4 The length of pointer
 printf("strlen(arr) = %d /n", strlen(arr));   // strlen(arr) = 5 The length of array
}
int main(int argc, char **argv)
{
 Student stud;
 fn(&stud);

 fnArray("Hello");
    return 0;
}