Article View: fr.comp.lang.c
Article #15044Re: Insérer une fonctions dans une structure?
From: Pierre Maurette
Date: Sat, 15 Oct 2005 18:31
Date: Sat, 15 Oct 2005 18:31
41 lines
2572 bytes
2572 bytes
frederic@askme.fr, le 15/10/2005, a �crit :
> Bonjour,
>
> y-a-t'il moyen en C, d'ins�rer une ou des fonctions dans une structure de
> donn�es?
>
> typedef struct Complex Complex;
> struct Complex {
> int value;
> int (*fn)();
> char *mesg;
> };
Oui, c'est possible, c'est m�me facile. Vous aviez bien commenc�. Ce
qui reste � faire, c'est initiliser et utiliser les membres fn de vos
structures.
Le plus simple pour initialiser C.fn, c'est de lui affecter l'adresse
d'une fonction fonct. On peut pour cela utiliser indiff�remment fonct
ou &fonct. Cette facilit� - que je trouve regrettable, mais c'est un
troll - n'est pas unique dans le langage.
Un code de test pourrait �tre (OK, le style est � chier):
int carre(int i) {return i * i;}
int cube(int i) {return i * i * i;}
enum {ONE = 10, TWO};
Complex table[] = {
ONE, &cube, "premier message",
TWO, &carre, "deuxi�me message",
};
printf("%d\t%d\t%s\n", table[0].value, table[0].fn(table[0].value),
table[0].mesg);
printf("%d\t%d\t%s\n", table[1].value, table[1].fn(table[1].value),
table[1].mesg);
Comme plusieurs fois signal�, soyez prudent avec les nommages. double
doit �tre proscrit, et je n'aime pas trop Complex dans ce contexte.
--
Pierre Maurette
Technical Details
Message-ID:
<mn.7ccf7d5a1b906ca4.31483@laposte.net>Path:
arc1-ca.pugleaf.net!g2news1.google.com!news2.google.com!proxad.net!infeed-1.proxad.net!news18-e.free.fr!not-for-mailReferences:
<87r7amd6qx.fsf@venus.net>Show Full Headers
Complete Article Headers
X-Google-Thread: f9822,d00d98e8032f6fc
X-Google-Attributes: gidf9822,public
X-Google-Language: FRENCH,ASCII
Path: arc1-ca.pugleaf.net!g2news1.google.com!news2.google.com!proxad.net!infeed-1.proxad.net!news18-e.free.fr!not-for-mail
Subject: Re: Insérer une fonctions dans une structure?
From: "Pierre Maurette" <maurettepierre@wanadoo.fr>
References: <87r7amd6qx.fsf@venus.net>
Newsgroups: fr.comp.lang.c
Message-ID: <mn.7ccf7d5a1b906ca4.31483@laposte.net>
X-Newsreader: MesNews/1.04.00.00
Date: Sat, 15 Oct 2005 20:31:27 +0200
MIME-Version: 1.0
X-Face: cmi$3R1_J{[}5K|8d'LDiJ$SsZ*gn,j*PhJ#KVGt+45,E_N9O}GrhhQ>fb&q<&lz=g%PEv' u"m)N|KrBMux?2:E?N7Uw3L#H>L#GwM}<qH-?#_Y$B9]$q1"~iUGtN#HVy?}7.`m&iKF>gY:.`W.qu z`1'W'h-AXPmB]#7~<+@H.<0M`-jBkCWbmkcT_*LBVD3|p1a?h1H;cHq{$-vbeP@Hdcqp5z~lwU7ZK `~
Reply-To: maurettepierre@wanadoo.fr
Content-Type: text/plain; charset="iso-8859-15"; format=flowed
Content-Transfer-Encoding: 8bit
X-Antivirus: avast! (VPS 0541-3, 14/10/2005), Outbound message
X-Antivirus-Status: Clean
Lines: 43
Organization: Guest of ProXad - France
NNTP-Posting-Date: 15 Oct 2005 20:29:41 MEST
NNTP-Posting-Host: 84.7.248.203
X-Trace: 1129400981 news18-e.free.fr 4714 84.7.248.203:4827
X-Complaints-To: abuse@proxad.net