任何人都可以帮我编写这个 aadjacentElementsProduct 函数的主要函数吗? 问题是:
这是我尝试过的:
struct arr_integer
{
int size;
int arr[];
};
int adjacentElementsProduct(struct arr_integer inputArray);
int main()
{
int res,i;
struct arr_integer array;
printf("Enter size of the array: ");
scanf("%d", &array.size);
printf("Enter the elements in array: ");
for (i = 0; i < array.size; i++)
{
scanf("%d", &array.arr[i]);
}
printf("%d\n", array.arr[2]);
res = adjacentElementsProduct(array);
printf("Max is %d", res);
getch();
}
给定一个整数数组,找到具有最大乘积的一对相邻元素并返回该乘积。
示例
对于 inputArray = [3, 6, -2, -5, 7, 3],
输出应为 adjacentElementsProduct(inputArray) = 21
.
7
和 3
产生最大的乘积。
int adjacentElementsProduct(struct arr_integer inputArray)
{
int arrLength = inputArray.size;
int max = inputArray.arr[0] * inputArray.arr[1];
for (int i = 1; i < arrLength - 1; i++)
{
if (inputArray.arr[i] * inputArray.arr[i + 1] > max)
{
max = inputArray.arr[i] * inputArray.arr[i + 1];
}
}
return max;
}
最佳答案
结构成员arr
是flexible array member 。默认情况下,它没有分配大小,甚至没有分配内存,需要对其进行分配。这只能通过整个结构的动态分配来完成(例如使用malloc
)。
所以解决方案是这样的
struct arr_integer *array;
size_t array_size;
// Get the number of elements for the array
printf("Enter size of the array: ");
scanf("%zd", &array_size);
// Allocate memory for both the structure and the array data
array = malloc(sizeof *array + sizeof *array->arr * array_size);
array->size = array_size;
// Now you can initialize `array->arr[i]` for any `i` between `0` and `array->size - 1`
关于c - 结构体函数的传递和返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53540273/