我想将常量字符串const char * org
复制到char **cpy
,但我的代码不起作用。
我在想获取原始字符串的长度并使用malloc
动态分配内存,以便仅将*org
复制到**cpy
会起作用,但它没有。
我的错误在哪里?我不能使用strcpy
作为指向指针的指针,或者我该怎么做?
我对此很陌生,所以如果我没有看到非常简单的东西,我会提前道歉。
int string_dd_copy(char **cpy, const char * org)
{
int i = 0;
while(org[i] != ' '){
++i;
}
if(i == 0){
return 0;
}
*cpy = malloc(i* sizeof(char));
strcpy(*cpy, org);
printf("%s", *cpy);
return 1;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int string_dd_copy();
char **a;
char *b = "Iam";
string_dd_copy(a, b);
return 0;
}
int string_dd_copy(char **cpy, const char * org)
{
cpy = malloc(1 + strlen(org));
strcpy(*cpy, org);
return 1;
}
试试这个
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int string_dd_copy( char **cpy, const char *org )
{
if( strlen(org) == 0 ){
printf( "no datan");
return 0;
}
*cpy = malloc( strlen( org ) + 1 );
strcpy( *cpy, org );
printf("%sn", *cpy);
return 1;
}
int main()
{
const char *teststring = "hello world";
const char *noData = "";
char *testptr;
string_dd_copy( &testptr, teststring );
free( testptr );
string_dd_copy( &testptr, noData );
return 0;
}