简体   繁体   中英

pointer function in C not working

I intend to make my pointer print the value, but it just stops working (no error report from the MinGW) . . .

    #include<stdio.h>

    void point_here(int *yolo) {
      int you = 2014;
      yolo = &you;

    }


    main () {
      int *punk = NULL;

      point_here(punk);
      printf("Punk @ %d is not dead\w/.\n", *punk);

   }

How do I make this work? And why this does not work? Please explain. I'm new to pointers and C, and still confuse after reading stuff.

C is "call by value"; functions get copies of the caller's values, not references to them. If you change an argument inside the function, nothing happens in the caller's context.

To work around this you need explicit pointers, but even you still can't have a pointer to a local variable inside a function persist beyond the running of that function.

You're passing NULL as an argument to a function which effectively doesn't nothing. Then you try to dereference that NULL pointer which is illegal.

This modified version of your code works well:

#include <stdio.h>

void point_here(int *yolo) {
  *yolo = 2014;
}

int main () {
  int value = 0;
  int *punk = &value;
  point_here(punk);
  printf("Punk @ %d is not dead\w/.\n", *punk);
  return 0;
}

As others have said, you have the following issues:

  • Pointer to a function value doesn't work after the function finishes executing
  • You aren't passing the pointer to the pointer you are passing the pointer value. (In other words, you aren't editing what you think you are).

I fixed these two issues by passing in a pointer that has already been allocated, then you just modify it in the function. This is one standard way to use pointers. Best of luck!

There are 2 problems. First the pointer variable is pass by value, second the variable "you" is on stack which gets lost once the function returns.

Change the variable you to static like

static int you = 2014;

and change the argument to **yolo;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM