Monday, September 27, 2004

C: Functions that return pointers and function that return values of pointers

It might be a little simple if you're used to C, but it is not actually. Let's say:

  1. int Horrors( int * );
  2. int *Horrors2();
  3. int main(void) {
  4. int y = 5;
  5. int *ptrF = &y;
  6. Horrors( ptrF );
  7. int h = 5;
  8. Horrors( &h );
  9. *Horrors2();
  10. return 0;
  11. }

Line 1 declares a function that returns and integer value. Line 2 declares a variable that returns a pointer. Normally you'd return a pointer to a structure, so it makes sense to make a function that returns a pointer.

  1. int Horrors( int *a ){
  2. /*Returns the value of a pointer*/
  3. return *a;
  4. }
  5. int *Horrors2(void){
  6. /*Returns a pointer*/
  7. int a = 6;
  8. int *ptr = &a;
  9. return ptr;
  10. }

Not that line 4 returns the value of the variable a whereas line 10 returns a pointer to a.

No comments: