c - 使用指针在 C 中复制字符串不显示预期结果

标签 c arrays string pointers

我正在尝试使用指针实现一个字符串复制函数,如下所示:

#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 循环之后,您的 srcdst 将指向字符串末尾的空终止符,因此当你打印它们,它什么也不打印。相反,保留原始指针的副本并打印它们:

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/

相关文章:

c - 如何修复 `_meta' 的多个定义?

c++ - 我应该如何使用 openCV 创建矩阵数组

c++ - 将文件中的数据读取到类的数组中

.net - 从 VB.Net 中的二进制文件中提取字符串

php - 这段代码是什么意思 : `$Odd = ($Odd == "even") ? "odd": "even";` ?

C - 进程返回 139 (0x8B) 段错误

c - 输入年份,然后打印日历

c - 指针错误。一元 * 的类型参数无效

java - 如何将文件读入二维数组,无论它们在 java 中是空格还是换行符分隔?

ruby - 轨道 3 : is there way to automatically create a hash from a string representation of a hash