【问题标题】:Running a function defined in a struct运行结构中定义的函数
【发布时间】:2019-10-30 13:09:21
【问题描述】:

下面我会解释:

int jk = 0;
const int WAVFILE_SAMPLES_PER_SECOND = 44100;
struct waveform_data
{
    char *waves;
    double func;
};

struct waveform_data tag[] = {
    {"saw", (double) jk / WAVFILE_SAMPLES_PER_SECOND}, //This func
    {"triangle", ...},
    {"sawtooth", ...},
    {"NULL", 0}
};

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

    if (argc < 2){
        return 1;
    }

    char *waveform = argv[1];
    // Do a search of waveform
    for (int i = 0; i < 4; i++){
        if (!strcmp(waveform, tag[i].waves)){
            for (int g = 0; g < 30; g++){
                printf("%4f", tag[i].func);
                jk++; // modify the const jk means ERROR

            }
            break;
        }
        if (!strcmp(tag[i].waves, "NULL")){
            printf("waveform not found: %s\n", waveform);
            break;
        }
    }
}

所以我在struct waveform_data tag[] 中有这个函数(double) jk / WAVFILE_SAMPLES_PER_SECOND}

虽然我几乎完成了它,但这个函数希望jk 成为一个常量。如果我将其替换为 const,则无法使用 jk++ 修改它(在“//搜索波形”附近找到)。

那么我该如何解决它以使其接受非 const int?

编辑:问题是我不能在结构中声明一个函数。我只能在结构中存储指向函数的指针。

【问题讨论】:

标签: c


【解决方案1】:

在 C 中,不能在结构中声明函数。您可以将指向函数的指针存储在结构中。例如:

int jk = 0;
const int WAVFILE_SAMPLES_PER_SECOND = 44100;

double wavsaw(int i)
    {return ((double) i / WAVFILE_SAMPLES_PER_SECOND);}

struct waveform_data
{
    char *waves;
    double (*f)(int i);
};

struct waveform_data tag[] = {
    {"saw", wavsaw},
    {"triangle", ...},
    {"sawtooth", ...},
    {"NULL", 0}
};

并调用为:

tag[0].f(jk);

【讨论】:

    猜你喜欢
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多