What is the purpose of the sizeof command?

Asked

Viewed 7,055 times

4

What is the purpose of the command sizeof in c language?
I know I can use it to allocate memory and create vectors dynamically as follows vetInt = malloc(sizeof(int) * tamanho);.
Other than that this command has another function?

2 answers

6


The operator sizeof 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 for memory allocation and create vectors dynamically as follows vetInt = malloc(sizeof(int) * tamanho);

You should keep in mind that the command that actually makes the memory allocation is the malloc and not the sizeof, it only returns to the function malloc what size of variable it should allocate from memory.

  • Thank you for clarifying my doubt.

  • Most useful for this command?

  • @I don’t know any other.

  • I would like to make a correction. Sizeof does not return the required size, but the variable size.

2

Whenever you need to know the size of an object (or the number of sub-objects) you should use the 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 the 52 by a constant defined with a #define and use this constant (with a multiplication by sizeof *arr) in the malloc() and memcpy(), but, as I see it, this way is more pleasant.

Another example, to sort an array

int arr[52];
// preenche arr
qsort(arr, sizeof arr / sizeof *arr, sizeof *arr, fxcmp);
  • Thanks for the explanation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.