C语言中sizeof和strlen的使用

以下是 sizeof 和 strlen 的使用示例:

#include <iostream>

int main() {
    int num = 10;
    std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl;  // 输出 "Size of int: 4 bytes"
    std::cout << "Size of num: " << sizeof(num) << " bytes" << std::endl;  // 输出 "Size of num: 4 bytes"

    char str[] = "Hello";
    std::cout << "Size of str: " << sizeof(str) << " bytes" << std::endl;  // 输出 "Size of str: 6 bytes"

    return 0;
}
sizeof 可以直接计算类型或变量所占的字节数,无需额外的参数,可以用于基本类型、自定义类型、数组等。
#include <iostream>
#include <cstring>

int main() {
    const char* str = "Hello, World!";
    size_t length = strlen(str);
    std::cout << "Length of str: " << length << std::endl;  // 输出 "Length of str: 13"

    return 0;
}
strlen 需要以 null 结尾的字符数组(字符串)作为参数,返回字符串的长度,即不包括 null 终止符 \0 的字符个数。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值