Question

I send &s and char array(text) in function str_cpy

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

Examle(work):

   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");
}

Don't works (how it should work)

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);
}

How i can write last function? How correctly write function str_cpy or how send char array in function?

Was it helpful?

Solution

None of them would work. You need to allocate memory for s. Something like:

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);
}

OTHER TIPS

You should use an already alocated variable. The problem here is, when using a Pointer like:

char *pointer = NULL;

You're not having any physical memory address properly pointed. What you can do:

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.

If you dont want to use 2 variables, you can alocate memory for it.

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top