What is the purpose of the sizeof
command in C language ?
I know I can use it to allocate memory and dynamically create vectors as follows vetInt = malloc(sizeof(int) * tamanho);
. Otherwise this command has another function?
What is the purpose of the sizeof
command in C language ?
I know I can use it to allocate memory and dynamically create vectors as follows vetInt = malloc(sizeof(int) * tamanho);
. Otherwise this command has another function?
The sizeof operator indicates the size, in bytes, of the variable type. This operator allows you to avoid specifying computer-dependent data sizes in your programs.
When you say:
I know I can use it to allocate memory and dynamically create vectors as follows
vetInt = malloc(sizeof(int) * tamanho);
You should keep in mind that the command that actually does the memory allocation is malloc and not the sizeof , it just returns to the malloc What is the size of the variable that it should allocate from memory.
Whenever you need to know the size of an object (or the number of sub-objects) you should use sizeof
.
For example, to copy an array to an allocated memory zone
int arr[52];
p = malloc(sizeof arr);
if (p) {
memcpy(p, arr, sizeof arr);
// work with p
free(p);
}
In the example above, you can perfectly replace 52
with a constant set with a #define
and use that constant (with a% multiplication of%) in sizeof *arr
and malloc()
, but in my view , this way is nicer.
Another example, to sort an array
int arr[52];
// preenche arr
qsort(arr, sizeof arr / sizeof *arr, sizeof *arr, fxcmp);