(编辑)
在C中更新和返回函数中的字符串时可能会产生误解.
我是一名学生,刚刚开始try 动态内存分配技术.最近,我被告知要编写一个字符串复制()函数,该函数类似于<;string.h>;下C中的strcpy()函数.
它应该有两个参数:char c1[],char c2[]. Momentarily, I am focusing on a constraint wherein the length of string c1 is lesser than the string c2.在这种情况下,我们将把较大的字符串复制到较小的字符串中.因此,很自然,它将不得不扩大前一根弦的尺寸.(I have defined a function len() which returns the length of the string. It's working fine)
代码:
char* copy(char c1[],char c2[])
{
int i=0;
int lc1=len(c1);
int lc2=len(c2);
if(lc1<lc2)
{
//are the following two lines allowed?
c1=(char*) malloc(lc1*sizeof(char));
c1=(char*) realloc(c1,lc2*sizeof(char));
for(i=0;i<lc2;i++)
{
*(c1+i)=c2[i];
}
*(c1+lc2)='\0';
}
return c1;
}
*如果此代码有多个问题,我不会感到惊讶! * 我try 了如下测试:
#include <stdio.h>
#include <string.h>
#include "mystring.h"
main()
{
int i;
char s1[12],s2[12];
gets(s1);
gets(s2);
printf("copy: %s",copy(s1,s2));
printf("\ns1: %s",s1);
}
我得到了: output个
我希望两个输出是相同的,即副本和S1的输出.碰巧的是,只有当我将其与调用一起打印时,才会起作用.当我打印S1时,我以为它会打印副本.
我哪里错了?我认为这与我正在处理的变量的范围有关,或者与指针和内存分配作为一个整体有关!
EDIT:个 我制作了一个替代函数xCopy:
char* xcopy(char c1[])
{
int i=0;
int lc1=len(c1);
char* c2=(char*) malloc((lc1+1)*sizeof(char));
for(i=0;i<lc1;i++)
{
*(c2+i)=c1[i];
}
*(c2+lc1)='\0';
return c2;
}
I realised this function was not solving the actual problem.个
谢谢你的帮助!!