zl程序教程

您现在的位置是:首页 >  硬件

当前栏目

用 malloc 或 new 申请内存之后,应该立即检查指针值是否为 NULL

内存 是否 指针 检查 应该 null 之后 New
2023-09-14 09:12:03 时间

用 malloc 或 new 申请内存之后,应该立即检查指针值是否为 NULL。

防止使用指针值为 NULL 的内存。

 

 1 #include <iostream>
 2 #include <string.h>
 3 
 4 //main()函数
 5 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 6 using namespace std;
 7 int main(int argc, char** argv) {
 8         //声明字符数组
 9     char ch,string[80],*p;
10     int n;
11 
12     //输入字符串和要查找的字符
13     cout<<"Test strchr():"<<endl;
14     cout<<"string:";
15     cin>>string;
16     cout<<"ch    :";
17     cin>>ch;
18 
19     //在string中查找ch中的字符并显示
20     p=strchr(string,ch);
21     cout<<"p    :"<<p<<endl;
22 
23     //输入字符串和要查找的字符串并查找
24     char substr[80];
25     cout<<"Test strstr():"<<endl;
26     cout<<"substr:";
27     cin>>substr;
28 
29     //在string中查找substr中的字符串并显示
30     p=strstr(string,substr);
31     cout<<"p    :"<<p<<endl;
32     return 0;
33 }