zoukankan      html  css  js  c++  java
  • 一个教科书一般的“空指针”错误

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



  • 相关阅读:
    当别人疑惑时你坚定
    如何设置mvc的role和user
    在项目中添加引用的意思
    vs的使用技巧
    无法删除表实体的问题
    JavaScriptSerializer类
    统计代码行数&&遍历jQuery
    远程调用
    select、验证
    委托和事件的区别
  • 原文地址:https://www.cnblogs.com/javaadu/p/11742720.html
Copyright © 2011-2022 走看看