0

我发送&schar array(text)功能str_cpy

void str_cpy(char *str_in, char *str_out);

示例(工作):

   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 数组?

4

2 回答 2

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");
于 2013-10-17T12:36:13.080 回答
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);
}
于 2013-10-17T11:31:32.210 回答