c语言

如何正确使用c语言sizeof()

小樊
81
2024-09-08 22:41:00
栏目: 编程语言

sizeof() 是 C 语言中的一个运算符,它用于计算数据类型或对象所占用的内存字节数

  1. 计算基本数据类型的大小:
#include<stdio.h>

int main() {
    printf("Size of int: %lu bytes\n", sizeof(int));
    printf("Size of float: %lu bytes\n", sizeof(float));
    printf("Size of double: %lu bytes\n", sizeof(double));
    printf("Size of char: %lu bytes\n", sizeof(char));
    return 0;
}
  1. 计算结构体或联合体的大小:
#include<stdio.h>

typedef struct {
    int id;
    float score;
    char name[20];
} Student;

int main() {
    printf("Size of Student structure: %lu bytes\n", sizeof(Student));
    return 0;
}
  1. 计算数组的大小:
#include<stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("Size of array: %lu bytes\n", sizeof(arr));
    printf("Number of elements in the array: %d\n", n);
    return 0;
}

注意事项:

0
看了该问题的人还看了