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  对于内存管理、数据类型兼容性等方面都非常有用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++ 老炮儿的技术栈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值