一个教科书一般的“空指针”错误

#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;
}



原文地址:https://www.cnblogs.com/javaadu/p/11742720.html