Hi,
I have a propblem with a peace of CC code which is pretty standard for
common C. When I define a structure and point an array to a pre-defined
array;
struct {
string name;
double (*fn)(double);
} __fg_snd_[] =
{
{"lin", _fg_lin},
{"log", _fg_log10},
{"", NULL}
};
this works for C but not for CC?
Am I doing something wrong here, or doesn't CC allow this type of
declaration (and if not, is there an alternative)?
Erik
#include <stdio.h>
#include <math.h>
#include <string>
using std::string;
double _fg_lin(double v) { return v; };
double _fg_log10(double v) { return (v < 1) ? 0 : log10(v+1); };
struct {
string name;
double (*fn)(double);
} __fg_snd_[] =
{
{"lin", _fg_lin},
{"log", _fg_log10},
{"", NULL}
};
int main() {
double (*fn)(double) = NULL;
for (int j=0; __fg_snd_[j].fn; j++) {
printf("j = %i\n", j);
if (__fg_snd_[j].name == "log") {
fn = __fg_snd_[j].fn;
break;
}
}
if (!fn) {
printf("fn = NULL\n");
return -1;
}
printf("fn(0) = %f\n", fn(0));
printf("fn(10) = %f\n", fn(10));
return 0;
}
#include <stdio.h>
#include <math.h>
#include <string.h>
double _fg_lin(double v) { return v; };
double _fg_log10(double v) { return (v < 1) ? 0 : log10(v+1); };
const struct {
char name[3];
double (*fn)(double);
} __fg_snd_[] =
{
{"lin", _fg_lin},
{"log", _fg_log10},
{"", NULL}
};
int main() {
double (*fn)(double);
int j;
for (j=0; __fg_snd_[j].fn; j++) {
printf("j = %i\n", j);
if (!strncmp(__fg_snd_[j].name, "log", 3)) {
fn = __fg_snd_[j].fn;
break;
}
}
if (!fn) {
printf("fn = NULL\n");
return -1;
}
printf("fn(0) = %f\n", fn(0));
printf("fn(10) = %f\n", fn(10));
return 0;
}