The reason why sizeof(buf) is 500 in the c language main, but sizeof(buf) comes out as 4 in the function

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

#include <stdio.h>
void Load(char buf[])
{
    FILE* f = fopen("Test.txt", "r");
    fread(buf, sizeof(buf),1, f);
    printf("%s\n", buf);
    fclose(f);
}
void main()
{
    char buf[500] = {0};
    Load(buf);
}

In main, sizeof(buf) is 500, but in the function, sizeof(buf) comes out as 4. Can you tell me the reason?

c

2022-09-20 10:20

1 Answers

The buf in main is char buf[500]. At this point, size of (buf) is 500.

The buf in the function represents char buf[], which is a pointer variable that receives only the address value of the buf in the main. The pointer variable is usually 4 bytes in size, so the size of (buf) in the function is 4.

It is common to modify the function form as shown below and run Load(buf, sizeof(buf) in the main function to use the size value inside the function.

void Load(char buf[], int size)


2022-09-20 10:20

If you have any answers or tips


© 2022 pinfo. All rights reserved.