#include <stdio.h>
#include <afx.h>
/*void my_strcpy(char *s,char *t)
{
	int i = 0;
	while ((s[i] = t[i]) != '\0')
		i++;
}
*/
void my_strcpy(char *s,char *t)
{
	ASSERT ((s!=NULL)&&(t!=NULL));
	while ((*s = *t) != '\0')
	{
		s++;
		t++;
	}
}

int main()
{
	char *raw = "abcd";
	char *dest = NULL;
	printf("%s\n",raw);
	my_strcpy(dest,raw);
	printf("%s\n",dest);
	return 0;
}

指针,理论懂了,但是,用的时候一不小心就会犯错,这不,今儿我又来一出,记到这里,警示自己

正确的应该如下:

#include <stdio.h>
#include <afx.h>
/*void my_strcpy(char *s,char *t)
{
	int i = 0;
	while ((s[i] = t[i]) != '\0')
		i++;
}
*/
void my_strcpy(char *s,char *t)
{
	ASSERT ((s!=NULL)&&(t!=NULL));//使用断言进行入口检查
	while ((*s = *t) != '\0')
	{
		s++;
		t++;
	}
}

int main()
{
	char *raw = "abcd";
	char *dest = NULL;
	dest = (char *)malloc(4);//指针声明以后,一定要指向有意义的内存,才能使用,否则就是空指针。
	printf("%s\n",raw);
	my_strcpy(dest,raw);
	printf("%s\n",dest);
	return 0;
}



相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-07
  • 2022-12-23
  • 2021-12-28
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-01
  • 2021-06-21
  • 2021-08-29
  • 2021-09-22
  • 2021-11-26
  • 2022-12-23
相关资源
相似解决方案