C/C++语言常见陷阱(持续更新)

变量作用域
1
2
3
4
5
6
7
8
9
int x = 5;
int f() 
{
   int x = 3;       //此x在f作用域中将覆盖全局的x
   {
       extern int x;   //通过extern关键词引入文件作用域的x
       return x;        //于是此作用域内的想是全局的x
   }
}
以下代码中的输出语句输出0吗,为什么?
1
2
3
4
5
6
7
8
9
10
11
struct CLS
{
    int m_i;
    CLS( int i ) : m_i(i) {}
    CLS()
    {
        CLS(0); 
    }
};
CLS obj;
cout << obj.m_i << endl;

CLS(0);其实只是调用CLS(int)构造函数建立了一个局部对象,而默认构造函数其实相当于什么也没做。

函数指针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int foo();
 
int (*p)() = &foo;
cout<<p();
 
p = foo;
cout<<p();
 
p = *f;
cout<<*p)();
 
p = *******foo;
cout<<p();
//上述代码,每一对对指针的赋值和调用都是等价的
以下代码有什么问题?
1
2
3
4
5
6
7
8
9
10
11
12
13
struct Test
{
    Test( int ) {}
    Test() {}
    void fun() {}
};
void main( void )
{
    Test a(1);
    a.fun();
    Test b();
    b.fun();
}

Test b();编译器会把这一行当成一个函数声明,其返回值是一个Test对象。而不是生成一个对象b

问程序会在哪一行死掉
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct   S   
{      //! 炸弹加工厂!
        int   i;
        int * p;
};
void   main()
{
        S s;
        int *p = &s.i;  //! i地址付给s.p
        p[0] = 4;              //! 4赋给s.i
        p[1] = 3;              //! 3赋给s.p
        s.p = p;                //! s.i的地址赋给s.p
        s.p[1] = 1;            //! 1赋给s.p,即修改s.p本身
        s.p[0] = 2;            //! ......你觉得呢?
                              //! 问题就在这里,向内存0X00000001处写入值2,这是非法的!
}
下面两个函数有什么隐患
1
2
3
4
5
6
7
8
9
int Swap(int* x, int* y)
{
    if(x == NULL || y == NULL)
        return -1; 
    *x += *y; 
    *y = *x - *y; 
    *x -= *y; 
    return 1;
}

考虑x,y指向同一变量时候会发生什么?

下面两个函数有什么区别
1
2
3
4
5
6
7
8
9
void foo(int *x, int *y)
{   
    *x += *y;
    *x += *y;
}
void fun(int *x, int *y)
{   
    *x += 2 * (*y);
}

同上

不用循环,输出1~1000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct print
{
    static int m_n;
    print()
    {
        cout<<m_n<<' ';
        m_n++;
    }
};
 
int print::m_n = 1;
 
int main()
{
    print test[20];
    return 0;
}
判断单链表是否有环
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool
check (const node * head)
{
    if (head == NULL)
	return false;  //! 
    node *
	slow = head, *fast = head->next;
    while (fast != NULL && fast->next != NULL)  //! 没有环,最终会退出
      {
	  slow = slow->next;   //! 一快一慢两个指针,
	  fast = fast->next->next;   //! 如果有环,可在O(lgN)内相等
	  if (slow == fast)
	      return true;
      }
    return false;
}
下面程序有什么问题?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
	int n;
	string str;
	cin>>n;
	while(n--)
	{
		cin>>str;
		size_t cnt = 0;
		for(int pos = str.size() - 1; pos >= 0; --pos)
			if(isdigit(str[pos]))
				++cnt;
		cout<<cnt<<endl;
	}
	return 0;
}

[warning]This is original article, you could copy it freely with my site links!

posted @ 2011-04-14 23:26  心梦帆影  阅读(455)  评论(0编辑  收藏  举报