-1

I'll explain this below:

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;
        }
    }
}

So I have this function (double) jk / WAVFILE_SAMPLES_PER_SECOND} in struct waveform_data tag[].

While though I'm almost complete at it, this function wants jk to be a const. And if I replace it as const, then I can't modify it by using jk++ (found near at "//Do a search of waveform").

So how can I solve it so that it would accept non const int?

Edit: The problem is that I cannot declare a func inside a struct. I can only store a pointer to a function in a struct.

  • 2
    Possible duplicate of [Function pointer as a member of a C struct](https://stackoverflow.com/questions/1350376/function-pointer-as-a-member-of-a-c-struct) – Mgetz Oct 30 '19 at 13:23
  • @paul Very helpful indeed. I should try it. –  Oct 30 '19 at 13:23

1 Answers1

4

In C, you cannot declare functions in structs. You can store a pointer to a function in a struct. For example:

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}
};

and call as:

tag[0].f(jk);
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41