当我用char指针复制字符串时返回null

pep*_*som 1 c

我尝试用char指针复制字符串,程序没有给我什么,我不知道......

请让我知道我的代码问题.

int main() {
    char *a = "helloworld.txt";
    char *b = malloc( sizeof(char) * 20 );

    while(*a!='\0') {
        *b++=*a++;
    }
    *b = '.';
    b++;
    *b = '\0';

    printf("string: %s\n", b);
}
Run Code Online (Sandbox Code Playgroud)

结果是:

string: 
Run Code Online (Sandbox Code Playgroud)

Jab*_*cky 6

你需要这个:

int main() {
  char *a = "helloworld.txt";
  char *b = malloc( sizeof(char) * 20 );
  char *c = b;                  // save pointer to allocated memory

  while(*a!='\0') {
    *b++=*a++;
  }
  *b = '.';
  b++;
  *b = '\0';                    // b points to the end of the constructed 
                                // string now

  printf("string: %s\n", c);    // use pointer saved before instead of b
}
Run Code Online (Sandbox Code Playgroud)