Angus
Angus

Reputation: 12631

string copy function

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

This func works fine and prints the string. My doubt is as the pointer "dest" will be pointing to the '\0' how does it prints the whole string(as it didnt point to the initial address of the string).

Upvotes: 0

Views: 142

Answers (3)

Nik Bougalis
Nik Bougalis

Reputation: 10613

It's true that dest will point to the end of the string. But you are not printing the string by using dest - you are printing the string by using d which is a different variable.

Remember that in C and C++ values are passed by value by default - so when you call the function my_strcpy the value of the variable d is copied into the variable dest which is local to the function my_strcpy only and any changes to that variable will not affect d.

Also note that you are not allocating enough space for your d variable:

d = malloc(sizeof(char*));

This will allocate enough space for a pointer to character which will usually mean enough space for 4 (or maybe 8) characters. You should allocate enough space for the string you intend to copy plus one character for the terminating null byte. What is the size of the string you are trying to copy? Hint: strlen should help.

Upvotes: 1

ouah
ouah

Reputation: 145919

 my_strcpy(s,d);

C passes arguments by value. The value of d is passed to my_strcpy, which means d object inside main is not modified in your my_strcpy function.

Upvotes: 0

adelbertc
adelbertc

Reputation: 7320

The d pointer passed in is a copy of the pointer, so the position/movement of the pointer in your function is not reflected back to where it was called in main. While d and dest both point to the same block of memory (at least initially) and any changes to that block of memory will be reflected on both ends, the dest pointer is only a copy.

Upvotes: 0

Related Questions