C语言字符数组初始化和求长度

  • Post author:
  • Post category:其他


void CChartestView::OnDraw(CDC* pDC)
{
	CChartestDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	// TODO: add draw code for native data here
	char name[10];

	name[0]='a';
	name[1]='b';
	name[2]='c';
	pDC->TextOut(50, 50, name);

	char a[10];
    a[0] = 'i'; a[1] = ' '; a[2] = 'l'; a[3] = 'o'; a[4] = 'v'; 
    a[5] = 'e'; a[6] = ' '; a[7] = 'y'; a[8] = 'o'; a[9] = 'u'; 
    a[10] = '\0'; 
	pDC->TextOut(50, 80, a);

	char b[10];
    b[0] = 'i'; b[1] = ' '; b[2] = 'm'; b[3] = 'i'; b[4] = 's'; 
    b[5] = 's'; b[6] = ' '; b[7] = 'y'; b[8] = 'o'; b[9] = 'u'; 
	pDC->TextOut(50, 110, b);

	char c[] = "i believe you";
	pDC->TextOut(50, 140, c);
	CString str1;
	str1.Format("c的长度:%d", strlen(c));
	pDC->TextOut(200, 140, str1);

	char d[] = {'a', 'b', 'c', 'd','\0'};
	pDC->TextOut(50, 170, d);
	str1.Format("d的长度:%d", strlen(d));
	pDC->TextOut(200, 170, str1);

	char f[] = "上课睡觉觉";
	pDC->TextOut(50, 200, f);
	str1.Format("f的长度:%d", strlen(f));
	pDC->TextOut(200, 200, str1);
}

输出;

先看name,字符数组是按下标来赋值;

a也是,字符数组以 ‘\0’ 结束;

b的时候,出了一些问题,因为没有找到结束的 ‘\0’ ;

也可以如c一次性赋值,用strlen(c)求c的长度;

d赋了4个字符,和一个’\0’,输出d,再输出d的长度, d的长度是4;

如f,赋值中文也没问题;五个中文,字符数组长度为10;



版权声明:本文为bcbobo21cn原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。