What is the purpose of the sizeof command?

3

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?

    
asked by anonymous 22.08.2015 / 23:12

2 answers

5

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.

    
22.08.2015 / 23:25
2

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);
    
23.08.2015 / 09:10