c - struct 函数传递和返回
问题描述
谁能帮我编写这个 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
是一个灵活的数组成员。默认情况下,它没有为它分配大小甚至内存,它需要被分配。这只能通过整个结构的动态分配(使用例如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`
推荐阅读
- javascript - 图表js不显示图表
- firebase - 是否需要将 Firebase Analytics 添加到 build.gradle?
- python - 使用 Selenium 访问下一页上的元素
- javascript - 无法在 useEffect 中设置状态
- javascript - 从一个数组创建层次结构,该数组在属性中具有层次结构信息,该属性是带有分隔符“>”的字符串
- python - 考虑空节点,找到二叉树的两个节点之间的水平距离?
- javascript - 试图让我的删除按钮在 REACT 中工作
- javascript - HTML/JavaScript,如何将页面滚动到某个标签值?
- flutter - 在颤动的'FocusNode'中,脚手架的底部不起作用
- javascript - 如何在javascript中的ajax调用中获取错误的行号