Home > Software design >  Return pointer on 2d Array from a function
Return pointer on 2d Array from a function

Time:06-27

I'm new to C and trying to change the return type of a function. The problem is that, for example, these work:

float fct(int) 
float *fct(float)

But when I try to change the return type to:

float (*)[n]fct(int *n) 

The compiler issues an error:

error: expected identifier or ‘(’ before ‘)’ token

Even if it tells me to change the return type to float (*)[n].

It would be awesome if someone could explain what the issue is.

CodePudding user response:

What you are looking for is:

float (*fct(int *n))[SIZE];

I should note that the compiler won't like it if SIZE is not a constant value.

The pointer must have an identifier which in this case is fct(int *n), it's as if you had something like (*ptr)[SIZE] only ptr is fct(int *n).

The compiler message omits the pointer identifier, as usual. It just tells you what the type should be and that is float (*)[n]. If, for example, the return type was to be pointer to int it would tell you the return type should be int*.

Now, on a different note, n size doesn't make much sense because you use in the function as a parameter, as a pointer to int.

You must also be careful not to return a pointer to a locally (in the function) declared array, you will need to allocate memory for it if you want it to outlive the function.

  • Related