-1

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;
}
Prince
  • 119
  • 1
  • 8
  • 3
    `text1` needs to point to something. At the moment it's just an uninitialised garbage value. Try `char text1[128];` or `char *text1 = malloc(128);` – kaylum Jul 18 '21 at 07:54
  • I don't know about malloc function for now , I am a beginner , why text1 must point to something , is it not pointing to text2[0] after the strcpy function ? – Prince Jul 18 '21 at 07:58
  • 5
    Stack Overflow is not a replacement for existing C references. Please learn systematically from a C book or tutorial. This will be well covered in any such reference. – kaylum Jul 18 '21 at 08:01
  • 1
    `strcpy` as the name implies is making a **copy**. So of course the destination needs to have its own memory buffer. – kaylum Jul 18 '21 at 08:03
  • 1
    strcpy copies into existing allocation. This is how the function is implemented. Use strdup to allocate and copy in one step. However, you should learn about malloc and free before manipulate with pointers and memory. – kofemann Jul 18 '21 at 08:03

1 Answers1

3

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);
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63