我想创建一个函数来反转C中double数组的内容但它不起作用 我的函数没有返回反转数组?请帮忙
//Reverse the content of an array of double
#include<stdio.h>
#define SIZE 5
double *reverse(double *func[],int n);
int main()
{
int i;
double *arr[SIZE];
printf("Please enter 5 numbers\n");
for(i=0;i<SIZE;i++) {
scanf("%lf",arr[i]); // takes the the content of array
}
double arr = reverse(&arr,SIZE); // takes the return value from the function
for(i=0;i<SIZE;i++) {
printf("%.2lf\n",arr[i]);
}
}
double *reverse(double *func[],int n)
{
int i,j;
static double *base[SIZE];
for(i=4,j=0;i>=0,j<n;i--,j++) {
base[j] = func[i]; // reverses the content of array
}
return *base;
}
我想我的功能有问题,但我无法找到它
答案 0 :(得分:2)
您的代码存在许多问题。最重要的是:
double *arr[SIZE];
不 数组double (它是指向double的指针数组)。这种误解似乎贯穿了所有程序并导致其他一些错误。
例如:
scanf("%lf",arr[i]);
此处arr[i]
是未初始化的指针,因此扫描到它是未定义的行为。
此外,您的函数调用也会遇到数组错误。
更准确的代码版本可能是:
#include<stdio.h>
#define SIZE 5
void reverse(double* d, int n);
int main()
{
int i;
double arr[SIZE]; // Array of double
printf("Please enter %d numbers\n", SIZE);
for(i=0;i<SIZE;i++)
{
scanf("%lf", &arr[i]); // TODO: Check scanf return value....
// ^ Notice the & (i.e. address-of)
}
reverse(arr, SIZE); // Just pass arr as it will decay into a double pointer
for(i=0;i<SIZE;i++)
{
printf("%.2lf\n",arr[i]);
}
return 0;
}
void reverse(double* d, int n) // Just pass a pointer to first double in the array
{
int i, j=0;
double temp;
for(i=n-1; i>j; i--,j++) // Stop when you reach the middle of the array
{
// Swap using a temp variable
temp = d[j];
d[j] = d[i];
d[i] = temp;
}
}
答案 1 :(得分:0)
void reverse(double *arr,int n)
{
for(int i=0;i<n/2;i++)
{
double temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = arr[i];
}
}