当前位置: 首页 > backend >正文

sizeof的用途

sizeof  是 C 和 C++ 中的一个操作符,用于获取数据类型或者变量在内存中所占的字节数。以下是  sizeof  常见的用途以及对应的代码示例:
 
1. 获取基本数据类型的大小: sizeof  可以用来获取像  int 、 float 、 char  等基本数据类型在当前编译环境下所占用的字节数。
 
c   
#include <stdio.h>

int main() {
    printf("Size of int: %zu bytes\n", sizeof(int));
    printf("Size of float: %zu bytes\n", sizeof(float));
    printf("Size of char: %zu bytes\n", sizeof(char));
    return 0;
}
 
 
1. 计算数组的大小:通过  sizeof  计算数组在内存中占用的总字节数,结合  sizeof  计算单个元素大小,可得到数组元素个数。
 
c   
#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    size_t arr_size = sizeof(arr);
    size_t element_size = sizeof(arr[0]);
    size_t num_elements = arr_size / element_size;

    printf("Size of the array: %zu bytes\n", arr_size);
    printf("Size of each element: %zu bytes\n", element_size);
    printf("Number of elements in the array: %zu\n", num_elements);

    return 0;
}
 
 
1. 动态内存分配:在使用  malloc 、 calloc  等函数进行动态内存分配时, sizeof  用于确定要分配的内存大小。
 
c   
#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 5;
    int *ptr = (int *)malloc(n * sizeof(int));
    if (ptr == NULL) {
        perror("Memory allocation failed");
        return 1;
    }

    // 使用分配的内存
    for (int i = 0; i < n; ++i) {
        ptr[i] = i + 1;
    }

    // 释放内存
    free(ptr);

    return 0;
}
 
 
1. 获取结构体或类的大小:对于自定义的结构体或类, sizeof  可以用来计算它们在内存中所占的字节数。
 
c   
#include <stdio.h>

struct Person {
    char name[20];
    int age;
    float height;
};

int main() {
    struct Person p;
    size_t struct_size = sizeof(p);

    printf("Size of the Person struct: %zu bytes\n", struct_size);

    return 0;
}
 
 
1. 指针相关: sizeof  用于指针时,得到的是指针变量本身在内存中所占的字节数,而不是指针所指向的数据的大小。
 
c   
#include <stdio.h>

int main() {
    int num = 10;
    int *ptr = &num;

    size_t pointer_size = sizeof(ptr);

    printf("Size of the pointer: %zu bytes\n", pointer_size);

    return 0;
}
 
 
这些示例展示了  sizeof  在不同场景下的常见用途。在实际编程中, sizeof  对于内存管理、数据类型兼容性等方面都非常有用。

http://www.xdnf.cn/news/3633.html

相关文章:

  • 第 6 篇:AVL 树与 SB 树:不同维度的平衡探索 (对比项)
  • Redis源码阅读(一)跳表
  • P2196 [NOIP 1996 提高组] 挖地雷
  • Dify 安装 使用
  • 算法笔记.分解质因数
  • pytorch自然语言处理(NLP)
  • 一些读入时需要用到getchar()的时机
  • 微服务中组件扫描(ComponentScan)的工作原理
  • 序列数据(Sequential Data)​​:按顺序排列的动态信息载体
  • 深入拆解 MinerU 解析处理流程
  • 如何在linux服务器下载gitee上的模型
  • 【点对点协议(PPP)全解析】从原理到工程实践
  • JSON与字典的区别及示例
  • 数据结构6 · BinaryTree二叉树模板
  • 行业分析---速览2025上海车展
  • ESP-ADF esp_dispatcher组件之audio_service子模块回调管理函数详解
  • linux下如何在一个录目中将一个文件复制到另一个录目,删除目录
  • 【数据结构】堆的完整实现
  • Unity Text打字机效果,支持富文本
  • (11)Vue-Router路由的详细使用
  • SQL面试题——留存分析之使用bitmap 计算留存
  • 进程与线程:05 内核级线程实现
  • stm32教程:软件I2C通信协议 代码模板提供
  • Linux_su命令
  • 西电雨课堂《知识产权法》课后作业答案
  • 删除电脑中的AlibabaProtect
  • 论软件需求管理
  • LLMs Tokenizer Byte-Pair Encoding(BPE)
  • [ Qt ] | 第一个Qt程序
  • MySQL进阶(一)