tags:

views:

54

answers:

4

Hi,

I have a function returning float* where it's actually filled as an array in the returning function such that

float* some_fnc()
{
    float *x=malloc(sizeof(float)*4);
    x[0]=......
}
...
// in main
float y[4];
y=some_fnc();

however I get an "Incompatible types" error, is it normal? Is there a way to overcome this w/o declaring y as float* ?

A: 

You cannot modify the address of an array. Why don't you pass y as parameter to some_fnc? (or) you could just use the float pointer if you only knew the size at run time & not use the array in main.

naivnomore
+4  A: 

C doesn't support/allow assignment of arrays (even though it does support initialization of arrays, which can look like assignment). You have a number of choices available. One is to pass the address of the array to the function, and have it fill in the existing array instead of allocating space for it:

void some_func(float *array, int size) { 
    for (i=0; i<size;i++)
       array[i] = ...
// ...
}

Another possibility would be to just have a pointer in main to hold the pointer returned by the function:

float *y = some_fnc();
// use y. Note that array style notation (y[0], y[1], etc.) is still allowed.

// when you're done with y.
free(y);
Jerry Coffin
A: 

In your code you basically allocate two different arrays, one on the stack and the other one with malloc. Even if you could assign arrays in C (which you can't) the array allocated with malloc would be leaking memory each time you would call your function, so you definitively shouldn't do it that way.

So if you want to allocate your array on the heap with malloc, no there is no other way than to define it as float*. If you do so, don't forget to free it whence you don't need it anymore.

If on the other hand you really want an array on the stack (beware of possible stackoverflow) you have to pass this location into your function such that it may use it for your initialization code.

Jens Gustedt
A: 

As mentioned by others, you're trying to assign a pointer to an array and that doesn't work. If you really want to do this, you can use a struct instead.

struct foo { float f[4]; }

struct foo some_fnc()
{
    struct foo x;

    x.f[0] = 0.1;
    x.f[1] = 1.0;
    x.f[2] = 3.14159;
    x.f[3] = 42;

    return x;
}
...
// in main
struct foo y;
y = some_fnc();

Another option would be to pass the address of y to some_fnc:

void some_fnc( float x[4])
{
    x[0]=......
}
...
// in main
float y[4];
some_fnc(y);
tomlogic