我正在使用字符指针实现字符串复制功能,但它显示错误。这是代码:
#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;
}
最佳答案
char *t;
没有内存分配给你的指针,你正试图写入它会导致未定义的行为。所以分配内存
char *t = malloc(30); /* size of your choice or strlen(s) + 1*/
一旦使用完内存,使用
释放它free(t);
关于c - 使用字符指针复制字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28380998/