How can I get rid of the variable "temp" in this function?

From: William Payne (mikas_n_o_s_p_a_m_493_at_student.liu.se)
Date: 03/23/04


Date: Tue, 23 Mar 2004 01:56:32 +0100

Hello, considering the following function:

char* allocating_strcpy(char** destination, const char* source)
{
   char* temp = NULL;
   char* beginning = NULL;
   size_t length = get_length(source) + 1;

   beginning = *destination = malloc(sizeof(char) * length);

   if(*destination == NULL)
   {
      return NULL;
   }

   temp = *destination;

   for(; *source; source++, temp++)
   {
      *temp = *source;
   }

   *temp = '\0';

   return beginning;
}

How can I rewrite the function so I get rid of the "temp"-variable? I tried
the following but it segfaults when I run it. How can I correct it?

char* allocating_strcpy(char** destination, const char* source)
{
   char* beginning = NULL;
   size_t length = get_length(source) + 1;

   beginning = *destination = malloc(sizeof(char) * length);

   if(*destination == NULL)
   {
      return NULL;
   }

   for(; *source; source++, (*destination)++)
   {
      *(*destination) = *source;
   }

   *(*destination) = '\0';

   return beginning;
}

Thanks for any replies

/ A beginning C programmer



Relevant Pages