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

青灯夜游
Release: 2022-12-30 11:11:20
Original
15928 people have browsed it

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;
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template