zoukankan      html  css  js  c++  java
  • free 和delete 把指针怎么啦?

    别看 free 和 delete 的名字恶狠狠的(尤其是 delete),它们只是把指针所指的内存给 释放掉,但并没有把指针本身干掉。

    发现指针 p 被 free 以后其地址仍然不变(非 NULL),只是 该地址对应的内存是垃圾,p 成了“野指针”。如果此时不把 p 设置为 NULL,会让人误 以为 p 是个合法的指针。

     如果程序比较长,我们有时记不住 p 所指的内存是否已经被释放,在继续使用 p 之 前,通常会用语句 if (p != NULL)进行防错处理。很遗憾,此时 if 语句起不到防错作用, 因为即便 p 不是 NULL 指针,它也不指向合法的内存块。

     1 #include <iostream>
     2 #define size 5
     3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
     4 using namespace std;
     5 int main(int argc, char** argv) {
     6         //声明变量
     7     int i,j;
     8     float t,a[size];
     9 
    10     //从键盘上为数组赋值
    11     for (i=0;i<size;i++)
    12     {
    13        cout<<"a["<<i<<"]=";
    14        cin>>a[i];
    15     }
    16 
    17     //对数组按从小到大顺序排序
    18     for (i=0;i<size-1;i++)
    19         for (j=i+1;j<size;j++)
    20             if (a[i]>a[j])
    21             {
    22                t=a[i];
    23                a[i]=a[j];
    24                a[j]=t;
    25             }
    26 
    27     //显示排序结果
    28     for (i=0;i<size;i++)
    29        cout<<a[i]<<" ";
    30     cout<<endl;
    31 
    32     //输入要查找的数据
    33     int value;
    34     int found;   //找到为1,否则为0
    35     int    low,high,mid;   
    36     for (i=1;i<=3;i++) {
    37         cout<<"value=";
    38         cin>>value;
    39     
    40         //二分法查找数组a
    41         found=0;
    42         low=0;
    43         high=size-1;
    44         while(low<=high)
    45         {    
    46             mid=(high+low)/2;
    47             if (a[mid]==value)
    48             {
    49             found=1;
    50             break;
    51             }
    52             if (a[mid]<value)
    53                 low=mid+1;
    54             else
    55                 high=mid-1;
    56         }
    57         if (found)
    58             cout<<"The valu found at:a["<<mid<<"]="<<a[mid]<<endl;
    59         else
    60             cout<<"The "<<value<<" is not found!"<<endl;
    61     }
    62     return 0;
    63 }
  • 相关阅读:
    Sign in with the app-specific password you generated. If you forgot the app-specific password or need to create a new one, go to appleid.apple.com
    Java Web项目搭建过程记录(struts2)
    微信小程序之菜鸟入门教学(二)
    微信小程序之菜鸟选手入门教学(一)
    html 表单input录入内容校验
    VUE中使用driver.js实现先手引导
    BScroll使用
    VUE使用screenfull实现全屏
    VUE打印功能
    VUE中使用XLSX实现导出excel表格
  • 原文地址:https://www.cnblogs.com/borter/p/9406430.html
Copyright © 2011-2022 走看看