Angus
Angus

Reputation: 12631

copying a contents of a pointer to another

#include<stdio.h>
#include<malloc.h>
void my_strcpy(char *sour,char *dest){
 if(sour == NULL || dest == NULL){
  return;
 }
 dest = sour;
}
int main(){
 char *d = NULL;
 char *s = "Angus Declan R";
 //d = malloc(sizeof(strlen(s)+1));
 //my_strcpy(s,d);
 d = s;
 printf("\n %s \n",d);
 return 0;
}

In this i'm trying to make the pointer "d" to point to the location of what the "s" is pointing to. Why is that its not pointing to the location.

Upvotes: 0

Views: 149

Answers (3)

Rahul Goutham
Rahul Goutham

Reputation: 50

here *d and *s are two pointers you are just copying the address which is stored in the s pointer which is pointing to an array and array contains "Angus Declan R" , d can't point to the address

when u are declaring/defining like

int *s="Angus Declan R"; ---> initially an array is created in the code segment(which is read only area)and s is now pointing to the base address of that array.even u can't access string directly using *s.u have only option printing/accessing using address.

the only reason is the array created in the code segment area of the memory.

here %s prints value/string/char by using a base address until a null value encounters. malloc is unnecessary, in void my_strcpy() dest = sour; is also unnecessary. it is just like d=s; .

pardon if explanation is not good.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225202

C is a pass-by-value language. This question of the C FAQ can answer your question. Note that even if you fix your function prototype, your algorithm isn't copying a string at all - just a pointer. You can just replace that call with:

d = s;

In your main function. The malloc is unnecessary, too - you're just leaking it.

Upvotes: 3

Mahesh
Mahesh

Reputation: 34655

It is because c language is pass by value. Instead pass the address of the pointer.

void my_strcpy(char *sour,char **dest)
// Condition checking and then do -
    *dest = sour ;

Upvotes: 2

Related Questions