通过在 Dynamic 中使用指针将一个字符串复制到另一个字符串

标签 c string pointers dynamic

试图将一个字符串复制到另一个字符串。作为一个基础学习者,我已经尽最大努力从我这边获得输出,但在程序结束时(point1)我的逻辑无法正常工作。请引用下面给出的我的输入和输出以获得清晰的想法。

这个程序复制一个字符串。

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

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

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

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

    printf("Enter the P1 String\n");
    fflush(stdin);
    gets(p1);

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

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

    printf("Enter the P2 String\n");
    fflush(stdin);
    gets(p2);

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

    for(int i=loc-1;i<=n1;i++) //point 1
    {
       *(p1+i) = *(p1+i)+n2;
    }

    for(int i=0;i<=n2;i++)
    {
       *(p2+i) = *(p1+i)+loc;
    }

    printf("\n Final copy is\n");
        printf("%d",p1);

    free(p1);
    free(p2);

    return 0;
}

预期:

Input:
google
microsoft

output:
Goomicrosoftgle

实际:

Input:
google
microsoft

output:
[Some garbage values including given string]

最佳答案

  • 首先,不要按原样使用gets() unsafe使用并弃用
  • p1p2 在内存中动态分配,它们有自己的大小 n1n2分别。因此,当您将更多字符从 p2 添加到 p1 时,输出的大小需要增加,否则它们将无法容纳在该内存空间中
  • 对于使用 scanf 的字符串输入,分配的内存必须比实际长度多 1,因为在末尾插入一个空终止字符
  • 在最后的打印语句中,您使用的是 %d,它是整数类型的格式说明符,因此您应该使用 %s,因为您正在打印整个字符串

所以,这应该可行:

#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 + 1) * sizeof(char));

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

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

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

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

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

    output = malloc((n1 + n2 + 1) * sizeof(char));

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

    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;
}

这是输出:

Enter size of p1: 6
Enter the P1 String: google

Enter the size of p2: 9
Enter the P2 String: microsoft

Enter the Location to copy: 3

Final copy is: goomicrosoftgle

关于通过在 Dynamic 中使用指针将一个字符串复制到另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58457465/

相关文章:

C++ 命令行调试参数

c++ - 更新 : program shows adress of fstream instead of the text file

c - open() 和 read() 系统调用...程序未执行

c - 如何在 c/c++(openssl) 中验证任何类型的证书?

c - 输出模运算

c - 给定一个指向结构的指针,我可以在一行中将聚合初始化器的结果分配给结构吗?

python - 在python中扩展内置类

java - 如何使我的字符串比较不区分大小写?

mysql - 计算mysql中blob数据类型的列中具有特定单词的行数

c - 将指针转换为 int 以从 C 中的 int 函数返回是否安全?