char *字符串的复制
=复制
首先考虑下方代码:
char animal[20] = "bear";
char * ps;
ps = animal;
cout << animal << " at " << (int*)animal << endl;
cout << ps << " at " << (int*)ps << endl;
结果为
bear at 0x63b7ffe30
bear at 0x63b7ffe30
注意,将animal赋给ps并不会复制字符串,而只是复制地址。这样,这两个指针将指向相同的内存单元和字符串。
获得字符串的副本
ps = new char[strlen(animal) + 1];
strcpy(ps, animal);
cout << animal << " at " << (int*)animal << endl;
cout << ps << " at " << (int*)ps << endl;
结果为,可以看到复制后字符串的地址不同。
cat at 0x63b7ffe30
cat at 0x15e3bbada40
strcpy的局限性
strcpy(animal, "a picnic basket filled with many goodies"); //可能animal空间不够
在这种情况下,函数将字符串中剩余的部分复制到数组后面的内存字节中,这可能会覆盖程序正在使用的其他内存。要避免这种问题,请使用strncpy()。 该函数还接受第3个参数-要复制的最大字符数。然而,要注意的是,如果该函数在到达字符串结尾之前,目标内存已经用完,则它将不会添加空字符。因此,应该这样使用该函数:
strncpy(animal, "a picnic basket filled with many goodies", 19);
animal[19] ='\0';

浙公网安备 33010602011771号