使用字符指针的字符串副本中的错误

Abi*_*ahi 1 c string pointers

我正在使用字符指针实现字符串复制功能,但它显示错误.这是代码:

#include<stdio.h>
#include<string.h>
int main()
{
    char *s="abc";
    char *t;
    while((*s)!='\0')
    {
        *t++=*s++;
    }
    *t='\0';
    printf("%s\n",t);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Gop*_*opi 7

char *t;
Run Code Online (Sandbox Code Playgroud)

没有内存分配给您的指针,并且您正在尝试写入它,这将导致未定义的行为.因此分配内存

char *t = malloc(30); /* size of your choice or strlen(s) + 1*/
Run Code Online (Sandbox Code Playgroud)

一旦完成使用内存释放它使用

free(t);
Run Code Online (Sandbox Code Playgroud)