Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Passing Pointers to Functions

When you pass a pointer to a function, that function can use the pointer to change data in the calling code. For instance, here’s an example that passes a pointer to a function that changes a variable:

  int data = 1;

  int* datapointer = &data;

  printf("Before changer(), data = %i\n",
    data);

  changer(datapointer);

  printf("After changer(), data = %i\n",
    data);

void changer(int* pointer)
{
  *pointer = 2;
}

To pass a pointer to a function:

  1. Create a new program named functionpasspointers.m.
  2. In functionpasspointers.m, enter the code shown in Listing 4.11.

    This code passes a pointer to a function named changer().

    Listing 4.11. Starting functionpasspointers.m.

    #include <stdio.h>
    void changer(int*);
    
    int main()
    {
      int data = 1;
    
      int* datapointer = &data;
    
      printf("Before changer(), data = %i\n",
        data);
    
      changer(datapointer);
    
      printf("After changer(), data = %i\n",
        data);
    
      return 0;
    }
           .
           .
           .

    Listing 4.12. The functionpasspointers.m program.

    #include <stdio.h>
    void changer(int*);
    
    int main()
    {
      int data = 1;
    
      int* datapointer = &data;
    
      printf("Before changer(), data = %i\n",
        data);
    
      changer(datapointer);
    
      printf("After changer(), data = %i\n",
        data);
    
      return 0;
    }
    
    void changer(int* pointer)
    {
      *pointer = 2;
    }
  3. Add the code for the changer() function, which changes the data back in the calling code (Listing 4.12).
  4. Save functionpasspointers.m.
  5. Run the functionpasspointers.m program.

    You should see the following:

    Before changer(), data = 1
    After changer(), data = 2
  • + Share This
  • 🔖 Save To Your Account