Search code examples
cstrcpy

Passing destination string as a pointer in strcpy


I recently came to know about a function called strcpy , the syntax of strcpy is char*strcpy(char * destination,const char * source) , so destination string can be a pointer to char , but the output of my code is null , why ?

#include <stdio.h>
#include <string.h>

//Compiler version gcc  6.3.0

int main()
{
  char *text1;
  char text2[]="ahhabsha";
  strcpy(text1,text2);
  printf("%s",text1);
  return 0;
}

Solution

  • so destination string can be a pointer to char

    No, the destination string can not be a pointer.

    The destination must be a consecutive memory area of type char. The first function argument is a pointer pointing to that area.

    Your code correctly passes a char pointer but the problem is that the pointer does not point to any memory.

    There are typically two ways to do that.

    1. Allocate dynamic memory like:

       char text2[]="ahhabsha";
       char* text1 = malloc(sizeof text2);  // or malloc(1 + strlen(text2));
       ...
       ...
       free(text1);
      
    2. Change text1 to be a char array instead of a char pointer

      char text2[]="ahhabsha";
      char text1[sizeof text2];
      

    In the second case text1 is automatically converted from "char array" to "char pointer" when you call strcpy

    BTW:

    On many system there is also the non-standard strdup function. It performs both memory allocation and string copy so you don't need to call strcpy. Like:

        char text2[]="ahhabsha";
        char* text1 = strdup(text2);
        printf("%s\n", text1);
        free(text1);