我正在尝试使用指针实现一个字符串复制函数,如下所示:
#include <stdio.h>
#include <stdlib.h>
void copyStringPtr(char *from, char *to);
int main()
{
char strSource[] = "A string to be copied.";
char strDestination[50];
copyStringPtr(strSource, strDestination); // Doesn't work.
return 0;
}
void copyStringPtr(char *src, char *dst)
{
printf("The destination was\t:\t%s\n", dst);
// for(; *src != '\0'; src++, dst++)
// *dst = *src;
while(*src) // The null character is equivalent to 0, so when '\0' is reached, the condition equals to 0 or false and loop is exited.
*dst++ = *src++;
*dst = '\0';
printf("The source is\t\t:\t%s\n", src);
printf("The destination is\t:\t%s\n\n", dst);
}
预期的输出是:
The destination was :
The source is : A string to be copied.
The destination is : A string to be copied.
但我得到的输出是:
The destination was :
The source is :
The destination is :
可以看出,即使源似乎也没有初始化值。我在这里做错了什么?
最佳答案
一个问题是您没有初始化 char strDestination[50];
。因此它不代表有效的字符串,当您尝试在此处打印它时:
printf("The destination was\t:\t%s\n", dst);
这是未定义的行为。您可以像这样初始化它:
char strDestination[50] = {'\0'};
这显式地将第一个 char
设置为 '\0'
,使其成为一个有效的字符串。然后数组的其余部分默认初始化为 '\0'
。
此外,在 while
循环之后,您的 src
和 dst
将指向字符串末尾的空终止符,因此当你打印它们,它什么也不打印。相反,保留原始指针的副本并打印它们:
void copyStringPtr(char *src, char *dst)
{
char* srcOriginal = src;
char* dstOriginal = dst;
...
printf("The source is\t\t:\t%s\n", srcOriginal);
printf("The destination is\t:\t%s\n\n", dstOriginal);
}
关于c - 使用指针在 C 中复制字符串不显示预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58023944/