sizeof("string") 以及字符数组使用字符串初始化

本文探讨了C语言中使用sizeof运算符处理字符串时的行为,包括对常量字符串求字节长度时自动追加的NUL字符、声明字符数组时的初始化方式以及数组剩余元素的默认初始化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. sizeof 对于常量字符串求字节长度时,注意C会对常量字符串追加‘\0’这样一个NUL字符(末尾已经有NUL字符),所以会比所见常量字串长度大1

2. 在声明字符数组中使用常量字符串string初始化时,如果声明中未指定数组长度,注意数组长度为sizeof("string")

3. 在声明字符数组中使用常量字符串string初始化时,如果声明中指定了数组长度,且长度大于字符串长度,则剩余数组元素初始化为NUL字符

下面一段code可见其结果:

#include 
#include 

int main()
{
	char str1[6] = "str";
	char str2[] = "str";
	char str3[] = "str\0";
	char str4[6];
	int i;

	printf("%s: sizeof(st): %ld, sizeof(st\\0): %ld\n",
		__func__, sizeof("st"), sizeof("st\0"));

	for (i = 0 ; i < sizeof(str1); i++)
		printf("str1[%d] = %c %s, ", i, str1[i], str1[i] == '\0' ? "is NUL": "");
	printf("\n");

	for (i = 0 ; i < sizeof(str2); i++)
		printf("str2[%d] = %c %s, ", i, str2[i], str2[i] == '\0' ? "is NUL": "");
	printf("\n");

	for (i = 0 ; i < sizeof(str3); i++)
		printf("str3[%d] = %c %s, ", i, str3[i], str3[i] == '\0' ? "is NUL": "");
	printf("\n");

	for (i = 0 ; i < sizeof(str4); i++)
		printf("str4[%d] = %c, ", i, str4[i]);
	printf("\n");

	exit(EXIT_SUCCESS);
}

执行结果:
main: sizeof(st): 3, sizeof(st\0): 4
str1[0] = s , str1[1] = t , str1[2] = r , str1[3] =  is NUL, str1[4] =  is NUL, str1[5] =  is NUL, 
str2[0] = s , str2[1] = t , str2[2] = r , str2[3] =  is NUL, 
str3[0] = s , str3[1] = t , str3[2] = r , str3[3] =  is NUL, str3[4] =  is NUL, 
str4[0] =  , str4[1] = �, str4[2] = ], str4[3] = , str4[4] = �, str4[5] = ,


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值