试图将一个字符串复制到另一个字符串。作为一个基础学习者,我尝试了最大的努力来获得输出,但是在程序的结尾(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()
因为使用不安全且已弃用p1
并p2
在内存中动态分配,并且它们各自的大小分别为n1
和n2
。所以,当你从添加更多的字符p2
为p1
,输出需要的尺寸要增加,否则他们将不适合在内存空间scanf
分配的内存进行的字符串输入,由于末尾插入了一个空终止符,因此必须比实际长度大一%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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句