-3

My character pointer points to some memorry say "Hello world" and i want to compare this with other pointer and later want to do strcpy. I sit possible to do with char *

char *A ="hello"
char *B ="";

strcmp(A,B); // this compares correctly because B points to diff string
strcpy(B,A); // will this statment copies the string alone or both will point to same memory
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Sijith
  • 3,740
  • 17
  • 61
  • 101

2 Answers2

5
char *B ="";

This means that B is a pointer and you have pointed to the constant string "".

Copy the A string to the B with strcpy(B,A);

This means that you are copying the string of A to the memory which the B is pointing (and B is pointing to a constant string) so this will cause undefined behaviour

To avoid a such problem the B pointer should be pointed to a memory space for example you can point the B to a dynamic memory space allocated with malloc:

char *B = malloc(10*sizeof(char));

and you can make the size of the memory exactely the same of A string size with:

char *B = malloc((strlen(A)+1)*sizeof(char));

The +1 is for the null terminator character for the string

Another solution to avoid the problem: Define the B as an array of chars and not as a pointer:

char B[10];
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

your code will compile successfully as strcpy needs destination and source char * as argument.

char * strcpy ( char * destination, const char * source );

but you will get segmentation fault when you execute it...bcoz B points to no where first you have to allocate block of memory where B points at, by B=malloc(6);

char *A ="hello";
char *B;

B = malloc(6);

strcmp(A,B);
strcpy(B,A);

once you do this, yes strcpy will copy a total new string. A and B both will point to two different locations.

Kinjal Patel
  • 405
  • 2
  • 7