首页 > 解决方案 > 使用动态函数复制字符串

问题描述

我试图将一个字符串复制到另一个字符串中。面临最终输出的问题。请参考预期输出和实际输出。

这是为了在另一个字符串之间复制一个字符串。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n1, n2, loc;
    char *p1, *p2, *output;

    printf("Enter size of p1: ");
    scanf("%d", &n1);

    p1 = malloc(n1 * sizeof(char));

    printf("Enter the P1 String: ");
    scanf("%s", p1);

    printf("\nEnter the size of p2: ");
    scanf("%d", &n2);

    p2 = malloc(n2 * sizeof(char));

    printf("Enter the P2 String: ");
    scanf("%s", p2);

    printf("\nEnter the Location to copy: ");
    scanf("%d", &loc);

    output = realloc(p1, sizeof(char) * (n1 + n2));

    for (int i = loc - 1; i <= n1; i++)
        *(output + i + n2) = *(p1 + i);

    for (int i = 0; i < n2; i++)
        *(output + i + loc) = *(p2 + i);

    printf("\nFinal copy is: ");
    printf("%s\n", output);

    free(p1);
    free(p2);
    free(output);

    return 0;
}

预计 I&O/P:

Size of string: 6
Enter string: google
size of 2nd string: 6
Enter string: amazon
Location to copy: 2
Final copy: goamazonogle

实际 I&O/P:

Size of string: 6
Enter string: google
size of 2nd string: 6
Enter string: amazon
Location to copy: 2
Final copy: goamazonW //Here W is the unknown value is printing instead of "ogle".

标签: cstringdynamicrealloc

解决方案


sizeof(char)始终为 1。您可以通过消除代码来简化代码。

一旦您知道要读取的字符串的大小,就无法使用scanf (3) 将它读取的输入限制为您分配的缓冲区的大小。一般来说,我们不依赖输入来准确地描述自己。

在您的情况下,即使描述准确,代码也不正确: scanf 承诺%s用 NUL 字符终止读取的字符串,因此您的 6 字节输入需要一个 7 字节缓冲区来容纳该 NUL。这是一个错误。

有一种奇特的方法可以让 scanf 为您分配字符串内存。不过,传统上,您会使用getline (3) 来获取它,并使用strlen (3) 来找出它读取了多少。

正如一条评论指出的那样,realloc (3) 使其第一个参数无效,这意味着p1在该调用之后不能依赖它。您真的想output成为一个单独的缓冲区,您将从p1和复制数据到其中p2

但是,一旦您分配了输出缓冲区,您可能会惊讶地发现sprintf (3) 是您的朋友。对该函数的一次调用,%.*s以及动态限制字符串输出的构造以及输入上的指针运算,将生成您需要的内容。


推荐阅读