#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char ca1[] = {'C', '+', '+'}; // no null, not C-style string
char ca2[] = {'C', '+', '+', '/0'}; // explicit null
char ca3[] = "C++"; // null terminator added automatically
const char *cp = "C++"; // null terminator added automatically
char *cp1 = ca1; // points to first element of a array, but not C-style string
char *cp2 = ca2; // points to first element of a null-terminated char array
const char *cp3 = "some value";
//cp3[2] = 'n';
//cp3 = ca1;
while (*cp3) {
// do something to *cp3,cp3自加1后,它所指向的字符串就变为"ome value"
printf("*cp3 = %s/n", cp3);
++cp3;
}
//-----------------------------------------------
const char *cp4 = "A string example";
const char *cp5 = "A different string";
int i = strcmp(cp4, cp5); // i is positive 1
i = strcmp(cp5, cp4); // i is negative -1
i = strcmp(cp4, cp4); // i is zero 0
//-----------------------------------------------
// Dangerous: What happens if we miscalculate the size of largeStr?
// 危险:如果错误计算largeStr的大小会发生什么?
// largeStr将保存cp4、空格和cp5
int Lenofcp4 = strlen(cp4);
printf("cp4的长度为:%d/n", Lenofcp4);
int Lenofcp5 = strlen(cp5);
printf("cp5的长度为:%d/n", Lenofcp5);
// 不幸的是我们经常算错需要操作的字符串的长度
// 同样地,如果 cp4 或 cp5 所指向的字符串大小中途发生了变化,
// largeStr 所需要的大小也会计算错误
char largeStr[16 + 18 + 2]; // will hold cp4 a space and cp5
strcpy(largeStr, cp4); // copies cp1 into largeStr
strcat(largeStr, " "); // adds a space at end of largeStr
strcat(largeStr, cp5); // concatenates cp2 to largeStr
// prints A string example A different string
cout << largeStr << endl;
//------------------------------------------
//char largeStr2[16+18+2]
//char largeStr2[16+1+19] // 根据strncat的特点
char largeStr2[18 + 19 + 3]; // to hold cp1 a space and cp2
// 该步完成之后,第17个字符等于0(即largeStr2[16] = 0)
strncpy(largeStr2, cp4, 18); // size to copy includes the null
// strncat中源串的首字符会覆盖目的串的终结符(null)
// 如果源串中的null字符出现在count之前,
// 则strncat只会附加从strSource到null的所有字符
// 如果count数目大于strSource的长度,则会用strSource的长度代替count
// 此时,第17个字符变成空格(" "),第18个字符(largeStr2[17] = 0)
// 显然strncat会寻找目的子串中的null,并以此作为开头,进行子串连接工作
strncat(largeStr2, " ", 3); // pedantic, but a good habit虽然繁琐,但是个好习惯
//同理,在strncat cp5的时候,也是从目的子串中的null(第18个字符largeStr2[17])开始的
strncat(largeStr2, cp5, 19); // adds at most 18 characters, plus a null
//综上所述,在处理C风格字串中使用strncat时,或者之前的strncpy时,
//一定要算上终结符null
//否则会造成strncat找不到null来连接字串,从而造成不可知错误
cout << largeStr2 << endl;
string largeStr4 = cp4;
largeStr4 += " ";
largeStr4 += cp5;
cout << largeStr4 << endl;
//printf("largeStr4 = %s /n", largeStr4);
return 0;
}