Home  >  Article  >  Backend Development  >  How to calculate the bytes occupied by an array in C language

How to calculate the bytes occupied by an array in C language

青灯夜游
青灯夜游Original
2021-01-07 11:29:5315786browse

The number of bytes occupied by an array in memory can be calculated using the sizeof operator. This operator is specially used to detect the space (number of bytes) occupied by a type or variable or array in memory; syntax "sizeof(x)", where x is a type name, variable name or array name, etc., can return the number of bytes occupied by x.

How to calculate the bytes occupied by an array in C language

The operating environment of this tutorial: windows7 system, c99 version, Dell G3 computer.

Related recommendations: C language video tutorial

Calculate how much memory space (number of bytes) an array occupies in C language

There is an operator sizeof in C language that is specially used to detect the space (number of bytes) occupied by a type, variable or array in memory. It can be used to directly detect the number of bytes occupied by an array in memory. .

The syntax rules are:

sizeof(x);

//识别没有歧义时也可写成:
sizeof x;

Parameters: x is a type name, variable name or array name, etc.

Return value: Returns the number of bytes occupied by x (int type ).

The following code can help understand:

#include "stdio.h"
struct X{
    int d;
    float t;
    double b;
    char n[100];
};
int main(int argc,char *argv[]){
    int a[]={1,2,3,4,5,6,7,8,9,10};
    double y=3.1415926;
    struct X t[3]={{0,0.0f,0.0,""},};//结构体数组属复杂类型
    printf("10 elements of int array needs %d bytes.\n",sizeof a);//检测整型数组
    printf("Double variables of type need %d bytes.\n",sizeof(y));//double类型变量
    printf("Type float need %d bytes.\n",sizeof(float));//float类型
    printf("Structure array 't[3]' need %d bytes.\n",sizeof t);//检测复杂类型
    return 0;
}

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of How to calculate the bytes occupied by an array 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