In the context of your post, it seems that you really want to determine the length of a string contained by a variable, as opposed to the size of the variable. sizeof
when applied to a pointer, will tell you the size of the address, not the length of the string. If you need to determine the length of a string at runtime, use the function strlen
:
`int len = strlen(some_str)`
You may be getting full_msg_size: 25 size of full_msg: 8 because sizeof
is returning the size of the address of full_msg
.
So, your function:
printf("size of full_msg: %d\n", (int*)sizeof(full_msg));
Should be:
printf("length of full_msg: %d\n", strlen(full_msg));
if you want to want to calloc 25 bytes of memory exactly:
char *full_msg = {0};
full_msg = calloc(25, 1); //all space initialized to 0
//or you can also use:
full_msg = malloc(25);
full_msg now has memory for exactly 25 bytes, (but one needs to be used for '\0')
The sizeof
operator when used on a char *str
, returns to you the size of a char *
, which is just an address.
Note: The size of an address (or pointer) will not always be 8 bytes just because you are running a 64 bit machine, it depends on what the application is compiled to: 32bit or 64bit. i.e., For a 32 but application, size of an address is 4 bytes, for a 64 bit application, it will be 8 bytes.