How to copy a string using a pointer

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

    Copy a string "constant/literal/pointer"

    char *str = "some string thats not malloc'd";
    char *tmp = NULL; 
    int i = 0; 
    for (i = 0; i < 6; i++) {
        tmp = &str[i];
    }
    printf("%s\n", tmp);
    

    Reversed

    char *str = "some stupid string"; 
    char *tmp, *ptr = NULL; 
    ptr = str;
    while (*str) { ++str; } 
    int len = str - ptr;
    int i = 0;
    for (i = len; i > 11; i--) {
        tmp = &ptr[i];
    } 
    printf("%s\n", tmp); 
    

    tmp = &blah[i] can be interchanged with tmp = &(*(blah + i)).

提交回复
热议问题