Search⌘ K

SIZEOF TO VARIABLES

Explore how using the sizeof operator on variables in C improves code safety by removing size dependencies in memory allocation and manipulation. Understand why sizeof calculates size at compile time and how this idiom simplifies updates when changing data types, ensuring safer and more maintainable code.

We'll cover the following...

Problem Context

In the C language, generality is usually spelled void*. This is reflected in the standard library. For example, the functions for dynamic memory allocation (malloc, calloc, and realloc) do not know anything about the types we are allocating storage for and return pointers to allocated storage as void*. The client has to provide the required size information to the allocation functions. Here’s an example with malloc:

C
#include<stdio.h>
#include<stdlib.h>
typedef struct HelloTelegram
{
const char* text;
const char* username;
int code;
} HelloTelegram;
int main() {
HelloTelegram* telegram = malloc(sizeof(HelloTelegram));
printf("%lu\n", sizeof(telegram));
printf("%lu\n", sizeof(HelloTelegram));
return 0;
}

Code like ...