开发者

C Instructions explanation

开发者 https://www.devze.com 2023-02-25 00:29 出处:网络
can any one explain the following instructions: int *c[10]; char *(**n)(void); float *(**r(void))[6开发者_运维问答];

can any one explain the following instructions:

int *c[10];

char *(**n)(void);

float *(**r(void))[6开发者_运维问答];


short *(**v(void))(int);


long *(*(*(*z)(void))[7])(void);


http://www.cdecl.org/ will explain all these statements. C Right-Left rule explains how to read C declerations pretty well. There are plenty of other resources available, notably in this question.


Since this is your homework you won't learn this by me telling you everything ;) But, one hint. You can create and pass pointers to functions in C, not just variables.

Function arguments of all but the first example are prototypes for function pointers.

Say we have a library for testing colours, we might want to allow the users of our library to provide custom ways of getting the name of the colour. We might define a struct for users to pass in containing callbacks we can call.

struct colour_tester {
  char *(*colour_callback)(void);    
}

// test the user's function if given
void run_test(struct colour_tester *foo ){
  // use the callback function if set
  if ( foo->colour_callback != NULL ){
    char * colour = (*foo->colour_callback)();
    printf( "colour callback returned %s\n", colour );
  }
}

Users of the library would then be free to define implementations of these callback functions and pass them to us as a function pointer.

#include <colour_tester.h>

char * get_shape_colour(){
  return "red";
}

int main ( int argc, char** argv ) {
  // create a colour tester and tell it how to get the colour
  struct colour_tester foo;
  foo.colour_callback = &get_shape_colour;
  run_test( &foo );
}

I've leave you to work out what is going on with the ones with extra numbers of *s.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号