将一个字符串复制到另一个
Copy one string into another
当下面的代码片段是 运行 时,它给出了某种段错误并且程序正在崩溃。
所以最初 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;
}
对于初学者,函数的第二个参数
void fun (char * input , char **input1) {
当您传递 char *
. 类型的表达式时, 具有类型 char **
char * temp3;
fun(temp , temp3);
所以程序已经有未定义的行为。你需要像
这样调用函数
fun(temp , &temp3);
函数内至少要写以下内容
size_t size = strlen(input) + 1;
*input1 = malloc(sizeof(char) * size);
memcpy( *input1 , input , size);
那就是你需要计算源字符串的终止零字符'[=20=]'
。
并且函数的第一个参数应该有限定符const
void fun ( const char * input , char **input1);
在程序结束时,您应该释放函数中分配的内存
free( temp3 );
检查内存是否分配成功会更安全。例如
void fun( const char * input , char **input1 )
{
size_t size = strlen(input) + 1;
*input1 = malloc(sizeof(char) * size);
if ( *input1 ) memcpy( *input1 , input , size);
}
主要你可以写
fun(temp , &temp3);
if ( temp3 ) puts( temp3 );
free( temp3 );
当下面的代码片段是 运行 时,它给出了某种段错误并且程序正在崩溃。 所以最初 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;
}
对于初学者,函数的第二个参数
void fun (char * input , char **input1) {
当您传递 char *
. 类型的表达式时, 具有类型 char **
char * temp3;
fun(temp , temp3);
所以程序已经有未定义的行为。你需要像
这样调用函数fun(temp , &temp3);
函数内至少要写以下内容
size_t size = strlen(input) + 1;
*input1 = malloc(sizeof(char) * size);
memcpy( *input1 , input , size);
那就是你需要计算源字符串的终止零字符'[=20=]'
。
并且函数的第一个参数应该有限定符const
void fun ( const char * input , char **input1);
在程序结束时,您应该释放函数中分配的内存
free( temp3 );
检查内存是否分配成功会更安全。例如
void fun( const char * input , char **input1 )
{
size_t size = strlen(input) + 1;
*input1 = malloc(sizeof(char) * size);
if ( *input1 ) memcpy( *input1 , input , size);
}
主要你可以写
fun(temp , &temp3);
if ( temp3 ) puts( temp3 );
free( temp3 );