Home  >  Article  >  Backend Development  >  How to use sizeof in c language

How to use sizeof in c language

下次还敢
下次还敢Original
2024-04-27 22:39:161055browse

sizeof Usage in C

sizeof is an operator used to determine the number of bytes that a data type or variable occupies in memory. It is a unary operator, and the parentheses can be data types or variable names.

Syntax:

<code>sizeof(数据类型/变量名)</code>

Usage:

  • Get the size of the data type:
<code class="c">int i;
printf("int 的大小:%d 字节\n", sizeof(int));</code>
  • Get the size of the variable:
<code class="c">int array[10];
printf("array 的大小:%d 字节\n", sizeof(array));</code>
  • Get the size of the pointer variable:
<code class="c">int *ptr;
printf("ptr 的大小:%d 字节\n", sizeof(ptr));</code>
  • Get the size of the structure or union:
<code class="c">struct person {
    char name[20];
    int age;
};

printf("person 结构体的大小:%d 字节\n", sizeof(struct person));</code>
  • Get the size of the array element type:
<code class="c">int array[10];
printf("array 元素类型的大小:%d 字节\n", sizeof(array[0]));</code>

Note:

  • sizeof operator returns a compile-time constant, not a run-time constant value. The
  • sizeof operator cannot be used to obtain the length of an array. The
  • sizeof operator cannot be used to obtain the size of a pointer variable to an array.

The above is the detailed content of How to use sizeof in c language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn