zl程序教程

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

当前栏目

使用调试器逐步跟踪程序

程序 跟踪 调试器 逐步 使用
2023-09-14 09:12:04 时间

我认识不少技术不错的 C++/C 程序员,很少有人能拍拍胸脯说通晓指针与内存管理 (包括我自己)。我最初学习 C 语言时特别怕指针,导致我开发第一个应用软件(约 1 万行 C 代码)时没有使用一个指针,全用数组来顶替指针,实在蠢笨得过分。躲避指针 不是办法,后来我改写了这个软件,代码量缩小到原先的一半。 我的经验教训是:

(1)越是怕指针,就越要使用指针。不会正确使用指针,肯定算不上是合格的程序员。

(2)必须养成“使用调试器逐步跟踪程序”的习惯,只有这样才能发现问题的本质。

 1 #include <iostream>
 2 
 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     char str[10];
 8     char *strip=str;
 9 
10     //输入输出
11     cout<<"str=";
12     cin>>str;      //用字符数组输入字符串
13     cout<<"str="<<str<<endl;
14     cout<<"strip="<<strip<<endl;
15     cout<<"strip=";
16     cin>>strip;     //用字符指针变量输入字符串
17     cout<<"str="<<str<<endl;
18     cout<<"strip="<<strip<<endl;
19 
20     //利用指针变量改变其指向字符串的内容
21     *(strip+2)='l';
22     cout<<"str="<<str<<endl;
23     cout<<"strip="<<strip<<endl;
24 
25     //动态为字符型指针变量分配内存
26     strip=new char(100);
27     cout<<"strip=";
28     cin>>strip; //用字符指针变量输入字符串
29     cout<<"str="<<str<<endl;
30     cout<<"strip="<<strip<<endl;
31     return 0;
32 }