我在功能&s
char array(text)
和str_cpy
void str_cpy(char *str_in, char *str_out);
Examle(工作):
void str_cpy(char *str_in, char *str_out);
int main(int argc, char *argv[])
{
char *s = NULL;
str_cpy(&s, "Hola Hola");
puts(&s);
system("PAUSE");
return 0;
}
void str_cpy(char *str_in, char *str_out) {
strcat(str_in, "Hello");
}
不能工作(它应该如何运作)
void str_cpy(char *str_in, char *str_out);
int main(int argc, char *argv[])
{
char *s = NULL;
str_cpy(&s, "Hola Hola");
puts(&s);
system("PAUSE");
return 0;
}
void str_cpy(char *str_in, char *str_out) {
strcat(str_in, str_out);
}
我怎么能写最后一个功能?如何正确编写函数str_cpy或如何在函数中发送char数组?
答案 0 :(得分:0)
他们都没有用。您需要为s
分配内存。类似的东西:
void str_cpy(char *str_in, char *str_out);
int main(int argc, char *argv[])
{
char *s = calloc(sizeof(char), 100); //for 100 chars string
//OR char s[100] = { 0 };
//------v pass s not &s
str_cpy(s, "Hola Hola");
puts(s); //similary use s not &s
system("PAUSE");
return 0;
}
void str_cpy(char *str_in, char *str_out) {
strcat(str_in, str_out);
}
答案 1 :(得分:0)
您应该使用已经分配的变量。 这里的问题是,当使用指针时:
char *pointer = NULL;
您没有正确指出任何物理内存地址。 你能做什么:
char string[32];
char *pointer;
pointer = string; // or pointer = &string[0], which is the same
str_cpy(pointer, "Something");
// Here, pointer holds a real address, so you can work with it.
如果你不想使用2个变量,你可以为它分配内存。
char *pointer;
pointer = (char *) malloc(strlen("Something")+1);
// Dont forget an extra byte for binary zero who will termine the string
// from now, pointer holds the address of a memory block. It means you can:
strcpy(pointer, "Something");