Search code examples
cstringfunctionpointersdynamic-memory-allocation

copy string function, copied string not printing in function itself


I am writing a program of copy string using pointers dynamically. The function is called from main() and copied string is displayed in main() but when I tried to display the copied string in the function itself then there is only cursor blinking.

Here's my code:

#include<stdio.h>
#include<stdlib.h>

void copystr(char *p,char *s);

int main ()
{    
    char str[50],*ptr,*p;
    printf("enter the string\n");
    gets(str);

    ptr=malloc(50*sizeof(char));
    copystr(ptr,str);

    getch();
    return 0;
}

void copystr(char *p,char *s)
{          
    s=malloc(50*sizeof(char));
    while(*s!='\0')
    {   *p=*s;
        s++;
        p++;
    }
    *p='\0';

    printf("copy string is  %s", p);   // if i display this printf in main 'p' prints fine, but here no output
    free(p);
}     

what could be the reason?


Solution

  •      printf("copy string is  %s", p);   // if i display this printf in main 'p' prints fine, but here no output
    

    Because p does not point at the beginning of the string in that function (even assuming you fixed the issue with s=malloc(50*sizeof(char))).

    Also if you:

       free(p);
    

    like you have it now, you won't be able to use the original ptr in main too.