欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > sizeof的用途

sizeof的用途

2025/5/3 13:45:01 来源:https://blog.csdn.net/qinfen123456/article/details/147662971  浏览:    关键词: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  对于内存管理、数据类型兼容性等方面都非常有用。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词