字符穿数组和字符数组的研究

#include<iostream>
using namespace std;
int stringLength(char* p);

int main() {
	//char str2[9] = "123456789";
	//定义为str[9]报:C++ a value of type cannot be used to initialize an entity of type"char(9)"
	//因为无法吧'\0'自动加入到字符串结尾
	char str1[] = "123456789";//字符串数组
	cout << "str1[]:" << str1 << endl;
	cout << "sizeof(str1):" << sizeof(str1) << endl;
	cout << "strlen(str1):" << strlen(str1) << endl;
	for (int i = 0; i < 10; i++)
	{
		cout << int(str1[i]) << " ";
	}
	cout << endl;
	/*
		str1[]:123456789
		sizeof(str1):10
		strlen(str1):9
		49 50 51 52 53 54 55 56 57 0
	*/
	char str2[15] = "123456789";
	cout << "str2[15]:" << str2 << endl;
	cout << "sizeof(str2):" << sizeof(str2) << endl;
	cout << "strlen(str2):" << strlen(str2) << endl;
	for (int i = 0; i < 15; i++)
	{
		cout << int(str2[i]) << " ";
	}
	cout << endl;
	/*
		str2[15]:123456789
		sizeof(str2):15
		strlen(str2):9
		49 50 51 52 53 54 55 56 57 0 0 0 0 0 0//发现没有使用的空间都是'\0'填充
	*/

	//总结:
	//sizeof()统计这个字符串数组占用的空间字节数
	//srtlen()只统计有意义字符的个数,不包括'\0'

	char str3[9] = { '1','2','3','4','5','6','7','8','9' };//字符数组
	cout << "str3[15]:" << str3 << endl;
	cout << "sizeof(str3):" << sizeof(str3) << endl;
	cout << "strlen(str3):" << strlen(str3) << endl;

	for (int i = 0; i < 9; i++)
	{
		cout << int(str3[i]) << " ";
	}
	cout << endl;

	/*总结:
		str3[15]:123456789烫烫烫烫烫?
		sizeof(str3):9
		strlen(str3):21
		49 50 51 52 53 54 55 56 57
		发现输出不对,strlen也不对,可以判断strlen是找'\0',判断字符长度,我把str[4]='\0'后,strlen(str3):3
		所以想用cout输出整个字符,字符结尾必须加上'\0'
	*/

	char str4[15] = { '1','2','3','4','5','6','7','8','9' };//字符数组
	cout << "str4[15]:" << str4 << endl;
	cout << "sizeof(str4):" << sizeof(str4) << endl;
	cout << "strlen(str4):" << strlen(str4) << endl;

	for (int i = 0; i < 15; i++)
	{
		cout << int(str4[i])<<" ";
	}
	cout << endl;
	/*
		str2[15]:123456789
		sizeof(str4):15
		strlen(str4):9
		49 50 51 52 53 54 55 56 57 0 0 0 0 0 0//可以看出数字空着的空间全部用'\0'填充
	*/

	return 0;
}
int stringLength(char* p) {
	int i = 0;
	while (*(p+i) != '\0') {
		i = i + 1;
	}
	return i;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值