C語言sizeof字符串能精確計(jì)算長(zhǎng)度嗎

小樊
81
2024-09-29 15:08:04
欄目: 編程語言

在C語言中,sizeof運(yùn)算符用于獲取數(shù)據(jù)類型或?qū)ο蟮拇笮。ㄒ宰止?jié)為單位)。對(duì)于字符串,sizeof運(yùn)算符返回的是字符串中第一個(gè)空字符(null terminator,‘\0’)之前的所有字符所占的字節(jié)數(shù)。

因此,sizeof不能精確計(jì)算字符串的長(zhǎng)度,因?yàn)樗话兆址?。如果需要?jì)算字符串的實(shí)際長(zhǎng)度(包括空字符),需要使用其他方法,如strlen函數(shù)。

示例:

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, World!";
    printf("Size of string: %zu bytes\n", sizeof(str));  // 輸出字符串的總字節(jié)數(shù),包括空字符
    printf("Length of string: %zu characters\n", strlen(str));  // 輸出字符串的實(shí)際長(zhǎng)度,不包括空字符
    return 0;
}

在這個(gè)例子中,sizeof(str)返回的是str數(shù)組的總字節(jié)數(shù),而strlen(str)返回的是字符串的實(shí)際長(zhǎng)度。

0