一级指针易犯错误模型
错误 模型 指针 一级
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)++; 不情况就申请一个临时变量,很简单。
相关文章
- Sqlserver 2016 R Service环境安装的各种错误(坑)解决办法
- 安装SQLserver2008时出现的错误
- Silverlight 应用程序中未处理的错误
- Google Earth Engine(GEE)——错误Cannot read property ‘getValue‘ of undefined
- MySQL 8 Public Key Retrieval is not allowed 错误的解决方法
- 微服务轮子项目(49) -常见JVM内存错误及解决方案
- npm install 报 npm ERR! cb()never called!的错误
- Tomcat 500错误 问题集锦
- android常见错误-Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
- 《精通Spring MVC 4》——1.7 错误与转码配置
- 转 MySQL 1064 You have an error in your SQL syntax 错误解决办法
- cxf整合spring错误为:cvc-complex-type.2.4.c
- STM32学习及应用笔记二:一次运算符优先级造成的错误
- mysql开启skip-name-resolve 导致root@127.0.0.1(localhost)访问引发的ERROR 1045 (28000)错误解决方案
- Opencv 4.1.0加载caffe crnn模型中错误纠正