0

Could anyone help me solve the error shown in the code below?

#include <iostream>
#include "FG.h"

struct pr { double (*fG[3]) (double, double, double, double*);};

int main()
{       


    double (*fG[3]) (double, double, double, double*);

    fG[0] = GX00;
    fG[1] = GX00;
    fG[2] = GX22;

    double prx[2] = {10, 1};
    struct pr params ={ fG };
    std::cout << params.fG[0]( 1 , 0.5 , 1, prx ) << std::endl;

    return 0;
}

compile:

$ g++ -c test.cpp 

test.cpp: In function ‘int main()’: test.cpp:15:25: error: array must be initialized with a brace-enclosed initializer

1
  • Welcome to SO. You should take the tour. Glad your problem was resolved. Commented Jul 15, 2013 at 4:06

2 Answers 2

4

You can't initialize one array from another in C (just like array assignment doesn't work). Try this instead:

struct pr params = { { &GX00, &GX00, &GX22 } };

Here's another way, using a custom constructor: http://ideone.com/blVBox

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is, that "reading" fG (as you do in struct pr params ={ fG };) won't give you a copy of the array but a copy of the first address of the array. It's comparable to the following Situation:

char  buffer[200] = "Test";
char *p = buffer;

In this Situation p stores only the first address of the buffer. To initialize the struct on the other Hand, you need to tell the Compiler for every element what should be stored. So the correct initialization for your struct is:

struct pr params ={ 
    { GX00, GX00, GX22 }
};

Further I'd recommend you typedef the function signature instead of replicatiing it over and over again. It makes the code much more readable:

typedef double (*tCallback) (double, double, double, double*);

struct pr {
    tCallback fG[3];
}

2 Comments

In your example, you get the address of the first element because you used the array in a context where it decays to a pointer. The code in the question is not such a context.
I wanted to point out the fact that you never get the contents of the whole array in the way the OP tried to get it. That's why I wrote "it won't give you a copy of the array". In the case of the OP's code fG also decays to a pointer initializing the first function pointer in the struct. (Which is obviously wrong)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.