LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-05-2019, 06:56 AM   #1
sibelius
Member
 
Registered: Oct 2018
Location: Leura NSW Australia
Distribution: Linux Knoppix 8.1
Posts: 53

Rep: Reputation: 0
C syntax question


Hi everyone.
I have a simple question about C syntax.

in the syntax of pointers to functions

type (*name)(type,type);

example 1)

int (*a) (int,double);

example 2)

double (*b) (int,int);

I declare a pointer variable to a single function.

in example 1), a pointer to a function that takes an int an a double and return an int.
in example 2), b is a pointer to a function that takes two int and return a double.


now if I write

int(*a [3])(int);

I have an array of three elements of pointers each one point to a function who takes in an int and return an int.


now if I write something like

int (*a[3])(int,double,float);
if the syntax is correct we have three pointer variables each one point to a function;
a[0] point to function that takes in an int, a[1] point to a function that takes a double and a[2] point to a function that takes a float and all return an int.
first question is:
is this syntax correct?


now let's suppose I have functions that takes in more then one type
for example f1 can take int and double or pointers as well and f2 takes something else how the syntax would be?

in my understanding is not possible in C for a function to return an array but is possible for a function to receive a pointer variable.

seems to me that the way to pass an array to one function to another function is threw this mechanism of a pointers to functions.

anyway any explanation would be very appreciate.
thank you very much in advance.
 
Old 09-05-2019, 07:31 AM   #2
rtmistler
Moderator
 
Registered: Mar 2011
Location: MA, USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 8,010
Blog Entries: 13

Rep: Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451
I realize this is not a direct answer, but from your question, there are numerous scenarios, or permutations here, and it all started with this:
Quote:
Originally Posted by sibelius View Post
I have a simple question about C syntax.
And an important point I see as part of your question is:
Quote:
Originally Posted by sibelius View Post
if the syntax is correct
So my first thoughts are:
  1. Why haven't you checked if the syntax is correct?
  2. Why haven't you written one or more sample programs to review all these permutations and reached some conclusions already?
You can do most anything with a programming language, and in my humble opinion, the C language gives you nearly infinite flexibility to declare things in very many ways, as well as a great deal of ways to "cheat", such as to use casting so that you can represent an array as a pointer for a passing argument, and then treat it as an array from within both the calling and called functions. And as you also mention, one can have pointers to functions, and pointers to pointers. Further, I've used the concept of registering callback functions for multiple use by interfacing code subsystems and many times void pointers are used to allow abstract pointers which can be nearly universally cast to other things.

Once again, not a direct answer, however my strong suggestions here are that you write some code to prove out any theories or to learn more about the topic, versus present to other people some high number of prototype permutations, along with a list of questions.
 
Old 09-05-2019, 08:13 AM   #3
NevemTeve
Senior Member
 
Registered: Oct 2011
Location: Budapest
Distribution: Debian/GNU/Linux, AIX
Posts: 3,844

Rep: Reputation: 1320Reputation: 1320Reputation: 1320Reputation: 1320Reputation: 1320Reputation: 1320Reputation: 1320Reputation: 1320Reputation: 1320Reputation: 1320
The syntax is correct but doesn't mean what you think it means. All three element of the array contains the same type of function-pointer:
Code:
int (*)(int,double,float)
 
3 members found this post helpful.
Old 09-05-2019, 09:30 AM   #4
GazL
LQ Guru
 
Registered: May 2008
Posts: 5,156
Blog Entries: 18

Rep: Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849
Code:
#include <stdlib.h>
#include <stdio.h>

int fn_both(int i, double d)
{
    printf ("%10s: %i, %f\n", "fn_both", i, d);
    return 0;
}

int fn_int(int i)
{
    printf ("%10s: %i\n", "fn_int", i);
    return 0;
}

int fn_double(double d)
{
    printf ("%10s: %f\n", "fn_double",  d);
    return 0;
}

int main()
{
    
    int (* fn[] )() = {fn_both, fn_int, fn_double};

    (* fn[0]) (0, 0.1);
    (* fn[1]) (1);
    (* fn[2]) (2.2);

    (* fn[0]) (2.2);   /* WTF! */
    return EXIT_SUCCESS;
}
Code:
$ cc -Wall fpointers.c && ./a.out
   fn_both: 0, 0.100000
    fn_int: 1
 fn_double: 2.200000
   fn_both: 0, 2.200000
$
I believe this is only working as an accident of the calling conventions on X86_64 (floats are passed in different registers). If the args were passed in order on the stack this would have fallen in a big heap!

Anyway, as can be seen, there's no argument checking, and this is ugly as hell! I'd recommend you find a better way: use va_args or a union to pass the data.
 
1 members found this post helpful.
Old 09-05-2019, 10:29 AM   #5
rtmistler
Moderator
 
Registered: Mar 2011
Location: MA, USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 8,010
Blog Entries: 13

Rep: Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451
Per the example you've provided GazL, that set of functions would best be served by overloaded functions in the C++ language.

I do fully concur that as coded now, it is messy.

I'm wondering if sibelius' question is academic, or if they are attempting to solve a technical problem.

If the latter, a technical problem, then I'd like to see additional information about this problem so as to understand why this is needed. As we know, there are multiple ways to design interfaces for things like callback function registrations, or similar things.
 
1 members found this post helpful.
Old 09-05-2019, 10:40 AM   #6
GazL
LQ Guru
 
Registered: May 2008
Posts: 5,156
Blog Entries: 18

Rep: Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849Reputation: 2849
Quote:
Originally Posted by rtmistler View Post
Per the example you've provided GazL, that set of functions would best be served by overloaded functions in the C++ language.
Yes, funnily enough I've been learning a little C++ over the last few days, and function overloading was one of the things that caught my attention and made me go Oooooooo!

To be honest, I was a little surprised to find that the above code even compiled without warnings!
 
Old 09-05-2019, 11:22 AM   #7
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 9,094

Rep: Reputation: 3931Reputation: 3931Reputation: 3931Reputation: 3931Reputation: 3931Reputation: 3931Reputation: 3931Reputation: 3931Reputation: 3931Reputation: 3931Reputation: 3931
https://cdecl.org/
 
1 members found this post helpful.
Old 09-05-2019, 11:56 AM   #8
rtmistler
Moderator
 
Registered: Mar 2011
Location: MA, USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 8,010
Blog Entries: 13

Rep: Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451Reputation: 3451
@dugan,

Quite interesting!

Half torn between bookmarking vs. not.

For me, why? A: And directly related more towards work, collaborative teams, and commercial code development. If the code is sufficiently obtuse, then I, or one of my peers, should not have written it, and we would not allow it to enter into our master branch without sufficient explanation, as well as defense that it was the only and also correct way to accomplish a design goal. Therefore getting an explanation from a site, because we could not decode it on our own, is not an ideal situation.
 
Old 09-06-2019, 07:25 PM   #9
sibelius
Member
 
Registered: Oct 2018
Location: Leura NSW Australia
Distribution: Linux Knoppix 8.1
Posts: 53

Original Poster
Rep: Reputation: 0
Good morning everyone.
thank you very much for all the reply.
i'd like to say that I absolutely agree with rtmistler that the best way to prove theory is to learn as much as you can on the topic.
I was reading about the syntax and as you suggested writing sample code to have a better understanding is the way to go, so once again I totally agree.
while I was writing this thread I was actually in the process to test the syntax by adjusting same codes.
so if you are asking yourself why I wrote the thread before checking, the best answer I can give is because not all my acts follows logic thoughts and also even if I understood same topic I have the ability to forget everything I learned and I have to start over and over, so that could be also an explanation of the fact I wrote if the syntax is correct, probably a few days ago I was reading about syntax and at the time I wrote this thread I wasn't sure anymore of what i read.

if someone wondering if is all about academic or technical problems the answer is no academic and no technical but simple mind hygiene.
in practice the main instrument I use is a piece of paper and a pen and after a few months of accumulating kilograms of notes I need to visualize a bit better were I'm going, so basically I try to code same simple algorithms to build same others.
in this process at the same time I'm learning C language (with the handicap of been logic at alternative phases but most of the time not coherent and discontinuous).

I have also to say that I find your replays very helpful because from them I pick hints in my learning process, if you still wondering about the logic or not logic of the contents you can also think at my thread as a therapeutic thread, so reply to my loud thoughts under form of thread is something like help a mental ill patient on his way to the toilet.

also the only persons involve in this life building project with no money involve (the consciousness of me and myself and not how to code algorithms in C language) is me and myself with your inestimable help and the support of a few other mental ill patients disseminate around the globe who became overtime so attached to me that just last night around 3 pm i got this phone call with the urge to know if in my opinion is close or open and due to the time when the question was made I can't remember what my answer was, and soon after I put down the phone.

I think at the moment I need to analyze all the suggestion you give to me and work with the help of myself and just in case same other illogical thread comes on your way please a beg you to believe that is not myself but only me.

I wish to all of you a nice day and maybe will interact again on the next thread.
thank you.

Last edited by sibelius; 09-06-2019 at 07:31 PM.
 
Old 09-11-2019, 03:34 AM   #10
bigearsbilly
Senior Member
 
Registered: Mar 2004
Location: england
Distribution: Slack, Debian, Mint, Puppy, Raspbian
Posts: 3,462

Rep: Reputation: 218Reputation: 218Reputation: 218
if you must use function pointers, best avoided for readability,
You can make things a lot clearer by using typedef so you only need to think about it once

Code:
 #include <stdio.h>

 typedef int (* iofunc ) (FILE * );

 int main(void)
 {

         iofunc array[] = { ferror, fileno, feof };


 }

Last edited by bigearsbilly; 09-11-2019 at 03:36 AM.
 
3 members found this post helpful.
Old 09-11-2019, 06:55 AM   #11
sibelius
Member
 
Registered: Oct 2018
Location: Leura NSW Australia
Distribution: Linux Knoppix 8.1
Posts: 53

Original Poster
Rep: Reputation: 0
thank you very much bigearsbilly for your help.
i'm starting to understand the mechanism you just wrote as a code, the output of most of my codes is right and is what I expect, on the way I'll try to write codes with less and less lines so learn more sophisticated mechanism is a must.
i'm planning to write a code to generate an object that represent a "flexible" euclidean space and a set of functions operating on it to "deform" this object in a certain way and if possible when the dimension is 3 to visualize the evolution of this object on an extra dimension.
from what rtmistler suggested on another thread I have already an idea how to approach the code problem.
anyway thank you again for you answer.
 
Old 09-11-2019, 08:34 AM   #12
bigearsbilly
Senior Member
 
Registered: Mar 2004
Location: england
Distribution: Slack, Debian, Mint, Puppy, Raspbian
Posts: 3,462

Rep: Reputation: 218Reputation: 218Reputation: 218
No worries!
the other BIG advantage of a typedef is you only need to change it in one place!

silly example!

Code:
#include <stdio.h>


typedef void (*bracer) (const char *);

void square (const char * s) { printf("[%s]\n", s); }
void lens (const char * s) { printf("(%s)\n", s); }
void curly (const char * s) { printf("{%s}\n", s); }


void map(char **argv, bracer func)
{
        while(*argv) {

                func(*argv); 
                argv++;
        }
}

int main (int argc, char ** argv)
{

        map(argv, square);
        map(argv, lens);
        map(argv, curly);
        return 0;

}
Code:
0:% $PWD/map What a load of rubbish       
[/home/billy/map]
[What]
[a]
[load]
[of]
[rubbish]
(/home/billy/map)
(What)
(a)
(load)
(of)
(rubbish)
{/home/billy/map}
{What}
{a}
{load}
{of}
{rubbish}

Last edited by bigearsbilly; 09-11-2019 at 08:35 AM.
 
2 members found this post helpful.
Old 09-11-2019, 03:53 PM   #13
sibelius
Member
 
Registered: Oct 2018
Location: Leura NSW Australia
Distribution: Linux Knoppix 8.1
Posts: 53

Original Poster
Rep: Reputation: 0
Very interesting example.
Thank you for the code.
 
Old Yesterday, 01:56 AM   #14
sibelius
Member
 
Registered: Oct 2018
Location: Leura NSW Australia
Distribution: Linux Knoppix 8.1
Posts: 53

Original Poster
Rep: Reputation: 0
thank you again bigearsbilly, I got in my head how this tool works.
Code:
#include <stdio.h>
#include <math.h>
//#define N 5000

unsigned int insert() {    
 	unsigned int a,n;
  	
  	printf("inserisci n deve essere >=2\n");
        scanf("%u",& n);   
  	printf("controlliamo se n e' pari o dispari\n");
  	printf("troviamo i numeri primi <= di n con il Crivello di Eratostene\n");	
  	
  	        a = sqrt (n);
  	        if(n==a*a)
  	        printf("il numero %u e' un quadrato perfetto\n",n);
  	
  		if (n%2 == 0)
  		printf("il numero %u e' positivo e pari\n",n);
  		else
  		printf("il numero %u e' positivo e dispari\n",n);
                                   
                                   return n;
                                   }


                        
unsigned int eratostene(unsigned int n)    {
                     
    int v[n - 1];
    unsigned int i;
    unsigned int j;
    for(i = 0; i < n - 1; ++i)
    {
        v[i] = i + 2;
    }
    i = 0;
    while(1)            //il C valuta 0 come falso e tutti gli altri numeri interi come vero
    {
        j = v[i] * v[i];
        if(j > n)
        {
            break;
        }
        do
        {
            v[j - 2] = 0;  //marco a 0 tutti i multipli
            j += v[i];
        }
        while(j <= n);
        while(v[++i] == 0);
    }
    
    printf("NUMERI PRIMI MINORI O UGUALI DI %u\n", n);
             for(j = 0; j < n -1; ++j) {
        if(v[j])
        {
           printf("%u ", v[j]);
        }
                                   }           
          printf("\n");
                                            
    return 0;
                                              }//end function



                           
int main() {
unsigned int (*apfunz[2]) (unsigned int) = {insert,eratostene};    //problema inizializzazione vettore puntatore
int i;
unsigned int n;


for(i=0;i<2;i++)

printf("%u\n",apfunz[i]);  //indirizzi del puntatore a funzioni
printf("\n");


(*apfunz[0])(12);         //richiamo funzione insert
(*apfunz[1])(12);         //richiamo funzione eratostene --calcola su n=12

return 0;   }

Last edited by sibelius; Yesterday at 01:59 AM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
httpd: Syntax error on line 210 of /etc/httpd/conf/httpd.conf: Syntax error on line 6 iswarya Linux - Newbie 1 01-25-2012 01:28 PM
[python] syntax Error : invalid syntax Python_user Programming 2 09-06-2009 12:52 PM
[SOLVED] "Error: syntax before '@' token and Error: syntax at 'OTHER' token" bullrider Programming 2 07-27-2009 08:00 AM
Starting httpd: httpd: Syntax error on line 209 of /etc/httpd/conf/httpd.conf: Syntax sethukpathi Linux - Networking 6 04-12-2008 11:26 AM
C++ syntax error before :: token HELP, i cant find the syntax error :( qwijibow Programming 2 12-14-2004 06:09 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:23 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration