#include<stdio.h>
void string_copy(char str1[],char str2[]);
int main()
{
        int i;
        char str1[10],str2[10];
        printf("please enter a name(string 1):");
        gets(str1);
        printf("please enter a name(string 2):");
        gets(str2);
        string_copy(str1,str2);
        printf("string 2 copied to string 1");
        for(i=0;i<10;i++)
        {
                printf("%c",str1[i]);
        }
        return 0;
}
void string_copy(char *p1,char *p2)
{
        int i;
        while((*p2)!='\0')
        {

                for(i=0;i<10;i++)
                {
                        *(p1)=*(p2);
                        p1++;
                        p2++;
                }
        }

}

I am getting segmention fault during output of the programm
please help me out of this

#include<stdio.h>
void string_copy(char str1[],char str2[]);
int main()
{
        int i;
        char str1[10],str2[10];
        printf("please enter a name(string 1):");
        gets(str1);
        fflush(stdin);
        printf("please enter a name(string 2):");
        gets(str2);
        fflush(stdin);
        string_copy(str1,str2);
        printf("string 2 copied to string 1: ");
        for(i=0;str1[i]!='\0';i++)
        {
                printf("%c",str1[i]);
        }
        return 0;
}
void string_copy(char *p1,char *p2)
{
        while((*p2)!='\0')
        {

            *(p1)=*(p2);
            p1++;
            p2++;

        }
        (*p1)='\0';

}

You are trying to access string areas beyond null in that for loop of yours in the copy function. The inner for loop is completely unnecessary.

hope this helps. SegFaults come when you try to access memory beyond the allocated or specified limit.

or simplified like below. Note the function is unsafe, just like strcpy(), because it blindly copys the characters from one string to another without regard to whether the destination string is large enough to hold them all. A better solution to that problem is the same as strcpy_s() -- pass another parameter which is the size of the destination buffer.

void string_copy(char *p1,char *p2)
{
        while(*p2)
           *pt1++ = *p2++;
        *p1 = '\0'; // null terminate the string
}

make your function as @Ancient Dragon says. and no need to print str1 using for loop in main function.
just use

printf("%s",str1);

Or better yet puts(str1);

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.