zl程序教程

您现在的位置是:首页 >  其他

当前栏目

一级指针易犯错误模型

错误 模型 指针 一级
2023-09-27 14:25:49 时间
#include	<stdio.h>

void	copy_str(char	*from, char	*to)
{
	//if (*from == '\0' || *to == '\0')
	if (from == NULL || to == NULL) //判断一个指针是否合法 是为了判断他是否是野指针, 而不是关心里面的内容
	{
		printf("func	copy_str()	err\n");
		return;
	}
	for (; *from != '\0'; from++, to++)
	{
		*to = *from;
	}
	*to = '\0';
}

char	*my_stract(char	*x, char*	y) //x = "123456\0",  y  ="abcd"
{
	char	str[80]; //"123456abcd\0 "
					 //           ↑
	char	*z = str;											/*指针z指向数组str*/
	while (*z++ = *x++);
	z--;																				/*去掉串尾结束标志*/

	while (*z++ = *y++);
	z = str;		  /*将str地址赋给指针变量z*/


	return(z);
}

int	main()
{

	char* x = "hello poem";
	char* y = "hello poet";

	printf("x+y is  %s\n", my_stract(x, y));

	char	*p = "aabbccdd";
	char	to[100] = { 0 };
	copy_str(p, to);
	printf("to	:	%s\n", to);


	return 0;
}

 



char	*my_stract(char	*x, char*	y) //x = "123456\0",  y  ="abcd"
{
	//char	str[80]; //"123456abcd\0 "
					 //    
	char* str = new char[50];
	char	*z = str;											/*指针z指向数组str*/
	while (*z++ = *x++);
	z--;																				/*去掉串尾结束标志*/

	while (*z++ = *y++);
	z = str;		  /*将str地址赋给指针变量z*/


	return(z);
}

int	main()
{

	char* x = "hello poem";
	char* y = "hello poet";

	printf("x+y is  %s\n", my_stract(x, y));

	return 0;
}

指针变量和其所指内存变量是两个不同的概念,应该判断指针变量是否为NULL,而不是其所指的内存变量,其所指的内存变量可以很多个‘\0’。

 

不要轻易的malloc因为还好释放,一般用buf[**]就可以。 a 已经发生偏移。

其值已修改,指到未尾了,再使用是空的。

临时变量空间,返回就清空了。

修改那后面的四个字节的数了,已经和*mycount值没有关系了。所以输出的是乱码。正确是(*mycount)++; 不情况就申请一个临时变量,很简单。