Home > other >  type pointer array size paranthesis meaning in syntax
type pointer array size paranthesis meaning in syntax

Time:04-29

I have a midterm in Saturday, so our teacher gave us the previous year's midterm to help. So there is a problem that I have trouble to understand. The question is 'fill the question marks so that program outputs the string 'accioccium'.

For who do not want to spend on solving, the answers are 1,2 and spell2.

So what is happening here? Especially, what is char* (*a[3]) (char *, char *)? I mean we are creating a char pointer array but what is that paranthesis at the end?

Also, a[0] = fun1 is weird too. Yes, you can assign variables by functions. However, there is no parameter here for fun1 function. Let us say parameters are constant as *s and *p. But this time, what are they?

#include <stdio.h>
#include <string.h>

char* fun1(char *s, char *p) {
    return s strspn(s,p);}

char* fun2(char *s,char *p) {
    return strcat(s,p);}

char* fun3(char *s,char *p){
    return strstr(s,p);}


char* (*a[3]) (char *,char *);

int main(void) {
    int i;
    char spell1[10] = "accio";
    char spell2[10] = "aparecium";
    char* result;

    a[0] = fun1;
    a[1] = fun2;
    a[2] = fun3;

    result = (*a[?]) (spell1, "c");
    printf("%s",result);

    result = (*a[?]) (?, "c");
    printf("%s",result);

    return 0;}

Thank you for your time and help.

CodePudding user response:

Especially, what is char* (*a[3]) (char *, char *) ? I mean we are creating a char pointer array but what is that paranthesis at the end?

It's an array of 3 pointers to function that takes 2 arguments pointer to char and returns a pointer to char.

The assignment a[0] = fun1 doesn't need the arguments, fun is not executed, only assigned to the compatible pointer a[0], you only add the parameters later when you actually want to execute the function, which is done for example in the line result = (*a[?]) (spell1, "c");

CodePudding user response:

char* (*a[3]) (char *,char *);

Starting from a and "going clockwise" or "picking things on the right first":

  • a

  • [ is array

  • 3]) of 3

  • (* pointers

  • (...) at end, to function

  • char *,char * taking two parameters of type char*

  • char* at the start, returning value of type char*

This matches signatures of fun1, fun2 snd fun3. and indeed array is filled with pointers to these 3 functions. Function name without () means pointer to function, it does not call the function, and using & to get address is not needed.

  • Related