[英]Copy one string into another
When the below piece of the code is run it is giving some kind of seg fault and program is crashing.当下面的代码运行时,它会给出某种段错误并且程序正在崩溃。 So initially temp = "abcdef" and finally temp3 should also contain "abcdef"
所以最初 temp = "abcdef" 最后 temp3 也应该包含 "abcdef"
My intention is to copy the content of "temp" into
"temp3".Please suggest where I am doing wrong.
void fun (char * input , char **input1) {
size_t size = strlen(input);
*input1 = (char **) malloc(sizeof(char) * (size+1));
memcpy(*input1 , input , size);
}
int main(){
char * temp = "abcdef";
char * temp3;
fun(temp , temp3);
printf("%s",temp3);
return 0;
}
For starters the second argument of the function对于初学者来说,function 的第二个参数
void fun (char * input , char **input1) {
has the type char **
while you are passing an expression of the type char *
.在传递
char *
类型的表达式时具有char **
类型。
char * temp3;
fun(temp , temp3);
So already the program has undefined behavior.所以程序已经有未定义的行为。 You need to call the function like
您需要像这样调用 function
fun(temp , &temp3);
Within the function you have to write at least the following在 function 中,您必须至少编写以下内容
size_t size = strlen(input) + 1;
*input1 = malloc(sizeof(char) * size);
memcpy( *input1 , input , size);
That is you need to count the terminating zero character '\0'
of the source string.也就是说,您需要计算源字符串的终止零字符
'\0'
。
And the first parameter of the function should have the qualifier const
function 的第一个参数应该有限定符
const
void fun ( const char * input , char **input1);
In the end of the program you should free the allocated memory in the function在程序结束时,您应该释放 function 中分配的 memory
free( temp3 );
It would be more safer to check whether the memory was allocated successfully.检查memory是否分配成功会更安全。 For example
例如
void fun( const char * input , char **input1 )
{
size_t size = strlen(input) + 1;
*input1 = malloc(sizeof(char) * size);
if ( *input1 ) memcpy( *input1 , input , size);
}
and in main you could write主要是你可以写
fun(temp , &temp3);
if ( temp3 ) puts( temp3 );
free( temp3 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.