我想将常量字符串const char * org
复制到char **cpy
,但是我的代码不起作用。
[我当时想获得原始字符串的长度,并使用malloc
动态分配内存,以便仅将*org
复制到**cpy
可以,但是没有用。
我的错误在哪里?我不能使用strcpy
作为指向指针的指针,或者我该怎么做呢?
我对此很陌生,所以如果看不到真正简单的东西,我会提前道歉。
int string_dd_copy(char **cpy, const char * org)
{
int i = 0;
while(org[i] != '\0'){
++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 data\n");
return 0;
}
*cpy = malloc( strlen( org ) + 1 );
strcpy( *cpy, org );
printf("%s\n", *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;
}
#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;
}