Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. pointer help

pointer help

Scheduled Pinned Locked Moved C / C++ / MFC
helpquestion
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Y Offline
    Y Offline
    yellowine
    wrote on last edited by
    #1

    I have the following codes: void Fun(int *v1, int *v2); int *n1 = 0; int main(int argc, char* argv[]) { int *n2 = new int; *n2 = 3; Fun(n1, n2); delete n2; return 0; } void Fun(int *v1, int *v2) { v1 = v2; } After compiled and run, the value of n1 is supposed to the pointer value of v2 which contains an integer 3 after called Fun and before the delete statement. But actually not, n1 is still 0 after called Fun. why? Thanks.

    S 1 Reply Last reply
    0
    • Y yellowine

      I have the following codes: void Fun(int *v1, int *v2); int *n1 = 0; int main(int argc, char* argv[]) { int *n2 = new int; *n2 = 3; Fun(n1, n2); delete n2; return 0; } void Fun(int *v1, int *v2) { v1 = v2; } After compiled and run, the value of n1 is supposed to the pointer value of v2 which contains an integer 3 after called Fun and before the delete statement. But actually not, n1 is still 0 after called Fun. why? Thanks.

      S Offline
      S Offline
      Saurabh Garg
      wrote on last edited by
      #2

      Thats is because if you pass an argument as pointer then only changes in the value of the argument will be preserved. If you want to change the pointer itself then you have to use double poitner.

      int *n1 = 0;
      void Fun(int **v1, int *v2)
      {
      *v1 = v2;
      }

      int main(int argc, char *argv[])
      {
      int *n2 = new int;
      *n2 = 3;

      Fun(&n1, n2);
      // n1 and n2 both point to same memory location here.
      delete n2;
      return 0;
      

      }

      -Saurabh

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups