0

I have function call as shown below:

void funCall(float *inp, int INPLen, float *out, char Case)
{
   if(case == 0)
   {
      memcpy(out, inp, INPLen*4);
   }
   else if(case == 1)
   {
      // Out will be result of arithmetic operations on **inp** 
       variable.
   }
}

In Case 0, if I use

Out = (float*) Inp;

, instead of memcpy, the variable Out is holding values of input only inside the function. What's the reason for it?

Are there any other way instead of memcpy?

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
user49626
  • 67
  • 4
  • `out` is a local variable. Changing it does not change the caller's value. Try `*out = *inp`. – kaylum Aug 29 '20 at 11:24

2 Answers2

0

In C parameters are passed by value. It means that they are actually copies of the variables used to call the function. Any modifications performed on them will be lost outside the function (that's exactly what you experience).

Pointers have to be used in case the desired behaviour is a modification of the parameter. So, if you need to modify an int, pass to the function its address (that will be a int *).

In your case you want to modify a pointer (float *) so you need to pass a double pointer float **).

So, just change out to float **:

void funCall(float *inp, int INPLen, float **out, char Case)
{
   if(case == 0)
   {
      *out = inp;
   }
   else if(case == 1)
   {
      // modify accordingly the way you access out
   }
}

Of course also the way you will call this function will change. Just as an example:

float in[3] = { 0.3, 3.45, 6.789 };
float *output;

funcall(in, 3, &output, 0);

So passing the address of output, a float *, we have a float **.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
0

Function parameters are function local variables that are initialized by copies of values of variables used as arguments.

So within the function there is changed the local variable out that was initialized by the value of the pointer passed to the function as an argument. The original pointer was not changed because the function deals with a copy of its value assigned to the pointer out.

To change an object you need to pass it by reference indirectly through pointer to it.

That is your function could be declared like

void funCall(float *inp, int INPLen, float **out, char Case);

and within the function you could write

*out = inp;

In this case the original pointer passed to the function indirectly through the pointer to it out of the type float ** would be changed within the function.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335