How to copy a string using a pointer

前端 未结 7 1529
野趣味
野趣味 2020-12-15 21:05

Here\'s a program I wrote to copy a string constant.

When the program is run it crashes. Why is this happening ?

#include 

char *alph         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 21:13

    cpy function will take two char pointers and the src pointer will point to the initial character of src(char array) defined in the main function, and same as the des pointer will point to the initial location of des(char array) defined in the main function and the while loop value of the src pointer will assign the value to des pointer and increment the pointer to the next element, this will happen until while loop encountered with null and comes out of the loop and des pointer will simply assigned null after taking all the values.

    #include
    void cpy(char *src,char *des)
    {
         while(*(des++) = *(src++));
         *des = '\0';
    }
    
    int main()
    {
         char src[100];
         char des[100];
         gets(src);
         cpy(src,des);
         printf("%s",des);
    }
    

    Output: Image

提交回复
热议问题