C - Passing a pointer to a function

Introduction

When passing a pointer to a function, the data that's modified need not be returned.

The function would reference a memory address, not a value directly.

By using that address, information can be manipulated without being returned.

Demo

#include <stdio.h> 

void discount(float *a); 

int main() /*  w  w w  .  j av  a  2s.c o m*/
 { 
    float price = 42.99; 

    printf("The item costs $%.2f\n",price); 
    discount(&price); 
    printf("With the discount, that's $%.2f\n",price); 
    return(0); 
} 

void discount(float *a) 
{ 
    *a = *a * 0.90; 
}

Result

The discount() function is prototyped and it requires a float type of pointer variable as its only argument.

Within the function, pointer variable a is used to peek at the value at the memory location that's passed.

Related Topic