Yet another “trick” that isn’t really a trick …

In my attempt to answer a question during my lecture this afternoon I typed in a quick-and-dirty program that was supposed to illustrate what I was saying. In the program I had to pass a variable number of struct pointers to a function, which I thought was a piece of cake. However, the straight-forward technique I’d been using made my poor students staring at the screen in disbelief. Although they would have had the technical background, they said they did not understand what I was doing.

What had struck them was something like this. (Note: I have changed the data type to int, and I have also simplified the code in function f to merely display the values passed, which hopefully will direct your attention to what is essential.)

#include <stdio.h>

void f( int* args ) {
  while( *args ) {
    printf( "%d ", *args );
    args++;
  }
  printf( "\n" );
}

int main( int argc, char* argv[] ) {
  f( (int[]){ 1, 5, 8, -2, 3, 6, 0 } );
  f( (int[]){ 3, -6, 2, 20, 0 } );
}

Function f is invoked by function main() twice. In both calls of f, a sequence of integer numbers (array literal) is type-casted to an array of int. Function f will now receive a pointer to a sequence (array) of int values. Hence, the argument of f must be an int pointer. Dereferencing this pointer will give us the first value. The number of values (or length of the array) is determined by the terminating zero.

This “trick” (which isn’t really a trick) is based on a principle that you have already used when passing a text strings to functions in C. Strings in C are arrays of characters, and any array is represented by a pointer that holds the address of its first element. So it doesn’t matter which data type you want to pass. Feel free to pass ints, doubles, or even struct pointers. Easy, isn’t it?

If you still do not feel comfortable with pointers, read this (Intermediate) or this (Introduction).

Have fun!

— Andre M. Maier

Advertisements

About bitjunkie

Teacher, Lecturer, and BITJUNKIE ...
This entry was posted in Pointers, Programming Essentials, Uncategorized. Bookmark the permalink.