【合集】【更新中】C++ pointer 之指针大乱指

来源:互联网 发布:程洁 人工智能 编辑:程序博客网 时间:2024/05/07 18:51

Problem 1: 

What's the result of the program:

class base {public:  ~base() {    printf("base disconcrete\n");  }};class child:public base {public:  ~child() {    printf("child disconcrete\n");  }};int main() {  base* b = new child();  delete b;  return 0;}

Take notice that base* points to derive, so :

Only 

"base disconcrete" is printed.

But if 

  child* c = new child();  delete c;

Problem 2:

char* getMem(void) {  char p[] = "hello world";  p[5] = 0x0;  return p;}void test(void) {  char *s = 0x0;  s = getMem();  printf(s);}int main() {  test();  return 0;}

The result is Not Sure

Problem 3:  Quite Dangerous

void f(char **p) {  *p += 2;}int main() {  char *a[] = {"123","abc","456"}, **r = a;  f(r);  printf("%s\r\n",*r);  return 0;}

The result is 3

But if 

void f(char **p) {  *p += 2;}void g(char **p) {  p += 2;}int main() {  char *a[] = {"123","abc","456"}, **r = a;  //f(r);  g(r);  printf("%s\r\n",*r);  return 0;}

The result is still 123

Only 

printf("%s\r\n",*(r+2)); output 456

Problem 4:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. class str{  
  2. public:  
  3.   int x;  
  4.   char s[0];  
  5. };  
  6.   
  7. class foo{  
  8. public:  
  9.   str * p;  
  10. };  
  11. int main() {  
  12.   foo f = {0};  
  13.   str* p1 = NULL;  
  14.   if (f.p->s){  
  15.     printf("%d\n", f.p->s);  
  16.   }  
  17.   return 0;  
  18. }  

This sentence sets p to NULL:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. foo f = {0};  

f.p is a pointer of str, so f.p is an offset. I.e., f.p->s = base address + 4

So the result is 4

Problem 5: Dangerous:

#include <stdio.h>#include <assert.h>int main(){    const int i = 10;     int* p = (int*)&i;    *p += 10;     printf("%d\t%d\n", i, *p);    printf("%x\t%x\n", &i, p); }

The value of i is 10, *p = 20. The address of i and p is same. 



But for struct. 

#include <iostream>#include <assert.h>using namespace std;struct mbLJ{    int mb;     int LJ;     mbLJ(){        mb=0;        LJ=1;    }   };int main(){    const struct mbLJ hehe;    int* p = (int*)(&hehe.mb);    *p += 10;     printf("%d\t%d\n", hehe.mb, *p);}输出 10 10

对全局变量取地址不会出错,对全局变量的const修改直接程序崩溃:

const int j = 10;int main(){    const int i = 10;     int* p = (int*)&i;    int* q = (int*)&j;        *q += 10;    //*p += 10;     printf("%d\t%d\n", i, *p);    printf("%x\t%x\n", &i, p);    //printf("%d\t%d\n", j, *q);    //printf("%x\t%x\n", &j, q);        return 0;}


#include <iostream>#include <assert.h>using namespace std;struct mbLJ{    static int mb ;     int LJ;     mbLJ(){        mb=0;        LJ=1;    }   };int mbLJ::mb  = 0;//没有这句编译不会过,因为静态成员变量只是声明,没有实现定义。。。int main(){    const struct mbLJ hehe;        int* p = (int*)(&hehe.mb);    *p += 10;     printf("%d\t%d\n", hehe.mb, *p);    return 0;}



2 0
原创粉丝点击