C和C++中的指针和动态内存

Adr*_*.S. 0 c c++ pointers dynamic-memory-allocation

几天前我不得不使用C,当使用指针时,我有点意外.

C中的一个例子:

#include <stdio.h>
#include <stdlib.h>

void GetPointer(int* p) {
  p = malloc( sizeof(int) );
  if(p) {
    *p = 7;
     printf("IN GetPointer: %d\n",*p);
  } else {
    printf("MALLOC FAILED IN GetPointer\n");
  }
}

void GetPointer2(int* p) {
  if(p) {
    *p = 8;
     printf("IN GetPointer2: %d\n",*p);
  } else {
    printf("INVALID PTR IN GetPointer2");
  }
}

int* GetPointer3(void) {
  int* p = malloc(sizeof(int));
  if(p) {
    *p = 9;
    printf("IN GetPointer3: %d\n",*p);
  } else {
    printf("MALLOC FAILED IN GetPointer3\n");
  }
  return p;
}

int main(int argc, char** argv) {
  (void) argc;
  (void) argv;
  int* ptr = 0;
  GetPointer(ptr);
  if(!ptr) {
    printf("NOPE\n");
  } else {
    printf("NOW *PTR IS: %d\n",*ptr);
    free(ptr);
  }

  int* ptr2 = malloc(sizeof(int));
  GetPointer2(ptr2);
  if(ptr2) {
    printf("NOW *PTR2 IS: %d\n",*ptr2);
    free(ptr2);
  }

  int* ptr3 = GetPointer3();
  if(ptr3) {
    printf("NOW *PTR3 IS: %d\n",*ptr3);
    free(ptr3);
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

IN GetPointer: 7
NOPE
IN GetPointer2: 8
NOW *PTR2 IS: 8
IN GetPointer3: 9
NOW *PTR3 IS: 9
Run Code Online (Sandbox Code Playgroud)

在此示例中,第一个指针在GetPointer方法内只有"value" .为什么malloc在内部使用仅持续该方法的生命周期?

我在C++中试过这个并且得到了相同的行为.我认为它会保留其价值,但不会.不过我找到了一条路:

void GetPointer(int*& p) {
  p = new int;
  if(p) {
    *p = 7;
     printf("IN GetPointer: %d\n",*p);
  } else {
    printf("MALLOC FAILED IN GetPointer\n");
  }
}
Run Code Online (Sandbox Code Playgroud)

在CI中无法做到这一点.有没有办法在C中做同样的事情或者我必须小心并在尝试给它一个值之前"malloc"指针?

Ton*_*ion 6

如果要重新分配指针指向C的内容,则必须使用int**,即指向指针的指针.

这是因为指针是作为参数复制的,所以如果希望指针指针中的更改在函数范围之外可见,则需要另一级别的间接.

  • 或者从函数返回新指针.我宁愿那样做. (3认同)