-4

Why it stops working? Can't we pass the name of the pointer as an argument for strcpy? if I change it to strcpy(&a,&b); it works.

#include <stdio.h>

    int main() {

    char *a;
    a = "aabtyn";

    char *b;
    b =  "mihli";

    strcpy(a,b);

    printf("%s-%s\n",a,b);


    return 0;
}
Varihlu
  • 57
  • 1
  • 9

3 Answers3

2

Can't we pass the name of the pointer as an argument for strcpy?

Yes, we can. However, it is also important that the destination pointer points to a writeable memory; in your case, neither a nor b point to memory that can be written.

if I change it to strcpy(&a,&b); it works.

If it appears to work on your system, it does so by mistake. What you see is undefined behavior. In order for strcpy to work you need to do one of the following:

  • Allocate a in automatic memory by defining it as char a[] = "aabtyn";, or
  • Allocate a in dynamic memory by calling char *a = malloc(7); You need seventh byte for null terminator.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

If you have:

char source[80],dest[80];

Initialize source, then:

strcpy(dest,source);

But if you have:

char *pd,*ps;

Initialize source,and malloc storage for *pd, then:

strcpy(&pd,&ps);

And remember to have free(pd); somewhere before exit(0);

Arif Burhan
  • 507
  • 4
  • 12
0

According to the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

You declared two pointers to string literals

char *a;
a = "aabtyn";

char *b;
b =  "mihli";

Then in this statement

strcpy(a,b);

you are trying to modify the first string literal. So the behaviour of the program is undefined.

As for this statement

strcpy(&a,&b); 

then there is an attempt to copy the value of one pointer to another pointer. This call aslo has undefined behaviour. But if the value of the second pointer is zero-terminated then this call can be equivalent to

a = b;

So the first pointer just reassigned. Though in any case there is undefined behaviour.

A valid program can look the following way

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

int main( void ) 
{
    char s[] = "aabtyn";

    char *a = s;

    char *b;
    b =  "mihli";

    strcpy(a,b);

    printf("%s-%s\n",a,b);

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335