I'm writing a function that returns the inverse of an array using recursivity but I keep getting these warnings:
Here is my code
#include <stdio.h>
#include <stdlib.h>
int inv( float* t[],int n)
{ float u;
if (n==0) return 0;
else
{
u=*t;
*t=*(t+n);
*(t+n)=u;
return(inv(*(t+1),n-1));
}
}
int main()
{
float t[]={1,2,3,4,5,6,7,8,9};
int n=sizeof t /sizeof *t;
int i=0;
inv(t,n);
for(i=0;i<n;i++)printf("%f",t[i]);
return 0;
}
int inv( float* t[],int n)
Here, float* t[]
declares an array of pointers. Please note that *t[i] = *(*(t+i))
For i = 0, *(*(t+i)) = *(*(t)) = *(*t)
.
Here, *t
is of type float*
, and u
is of type float.
Using the expression u=*t;
gives you that error (assigning float*
value to float
)
Solution: Change int inv( float* t[],int n)
to int inv( float t[],int n)
I use a procedure to arrange the array elements in descending order
#include <stdio.h>
#include <stdlib.h>
void revs(int i, int n, float *arr)
{
if(i==n)
{
return ;
}
else
{
revs(i+1, n, arr);
printf("%.f ", arr[i]);
}
return 0;
}
int main()
{
float t[]={1,2,3,4,5,6,7,8,9};
int n=sizeof t /sizeof t[0];
int i=0;
revs(0,n,t);
}
It looks like the intended action of OP's function inv
is to reverse the elements of an array of n
float
values in place, using recursion.
In the original inv
code, the parameter declaration float* t[]
will be adjusted to be equivalent to float** t
by the compiler. This needs to be changed to float t[]
or equivalently float* t
.
In the original inv
code, the return value is either 0
or the result of the recursive call to itself, which can only be 0
. Therefore the return value is of no use. It would be better to change the return type of the function to void
.
In the inv
function, the parameter n
is set to the length of the array in the initial call from main
. The function swaps the values of elements at indices 0 and n
before recursing, but there is no element at index n
. The last element has index n-1
. The function should swap the elements at indices 0 and n-1
before recursing. After swapping the first and last elements, the remaining n-2
elements with indices from 1 to n-2
can be swapped by a recursive call. The original inv
code uses the value n-1
in the recursive call, but it should be n-2
.
If n
is less than 2, the inv
function does not need to do anything.
A possible implementation of inv
based on OP's original code follows:
void inv(float* t,int n)
{
float u;
if (n>=2)
{
u=*t;
*t=*(t+n-1);
*(t+n-1)=u;
inv(t+1,n-2));
}
}
The same function can be written using array subscripting operators as follows:
void inv(float t[],int n)
{
float u;
if (n>=2)
{
u=t[0];
t[0]=t[n-1];
t[n-1]=u;
inv(&t[1],n-2));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.