我有一个这样的功能可以正常工作:
char* add(char* origText, char* paste)
{
char* pointerToOrigText = origText;
while (*pointerToOrigText!='\0')
pointerToOrigText++;
while (*paste!='\0')
*pointerToOrigText++=*paste++;
*pointerToOrigText='\0';
}
示例:origText = "abc", paste = "def"
后功能:origText = "abcdef", paste="def"
所以我将两个字符串合二为一。但是当我使用这个功能时:
char* add (char* origText, char *paste)
{
int newLength = strlen(origText) + strlen(paste)+ 1; // + '\0'
char* newText = new char[newLength]; // we want to make sure that 2 strings will fit.
char* pointerToNewText = newText; // pointer to char array where we will merge strings
char* helpPointer = origText; // helps us count until '\0'
while (*helpPointer!='\0')
{
*pointerToNewText=*helpPointer;
*pointerToNewText++; *helpPointer++;
}
while (*paste!='\0')
{
*pointerToNewText=*paste;
*pointerToNewText++; *paste++;
}
*pointerToNewText='\0';
origText = newText;
// cout <<origText<<endl;
}
外部函数的输出是:
- origText = “abc”,粘贴 = “def”
- 函数后:origText = "abc", paste = "def"
我的书解释说,这是因为这条线:
char* newText = new char[newLength];
但我不明白。为什么在函数中分配内存会影响指针 origText?