How to copy a string using a pointer

前端 未结 7 1526
野趣味
野趣味 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:37

    To perform such manual copy:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        char* orig_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char* ptr = orig_str;
    
        // Memory layout for orig_str:
        // ------------------------------------------------------------------------
        // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
        // ------------------------------------------------------------------------
        // |A|B|C|D|E|F|G|H|I|J|K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z |\0|  --> data
        // ------------------------------------------------------------------------
    
        int orig_str_size = 0;
        char* bkup_copy = NULL;
    
        // Count the number of characters in the original string
        while (*ptr++ != '\0')
            orig_str_size++;        
    
        printf("Size of the original string: %d\n", orig_str_size);
    
        /* Dynamically allocate space for the backup copy */ 
    
        // Why orig_str_size plus 1? We add +1 to account for the mandatory 
        // '\0' at the end of the string.
        bkup_copy = (char*) malloc((orig_str_size+1) * sizeof(char));
    
        // Place the '\0' character at the end of the backup string.
        bkup_copy[orig_str_size] = '\0'; 
    
        // Current memory layout for bkup_copy:
        // ------------------------------------------------------------------------
        // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
        // ------------------------------------------------------------------------
        // | | | | | | | | | | |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |\0|  --> data
        // ------------------------------------------------------------------------
    
        /* Finally, copy the characters from one string to the other */ 
    
        // Remember to reset the helper pointer so it points to the beginning 
        // of the original string!
        ptr = &orig_str[0]; 
        int idx = 0;
        while (*ptr != '\0')
            bkup_copy[idx++] = *ptr++;
    
        printf("Original String: %s\n", orig_str);   
        printf("Backup String: %s\n", bkup_copy);
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题