试图将一个字符串复制到另一个字符串。作为一个基础学习者,我已经尽最大努力从我这边获得输出,但在程序结束时(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使用并弃用 p1
和p2
在内存中动态分配,它们有自己的大小n1
和n2
分别。因此,当您将更多字符从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/