首页 > 解决方案 > 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 .

73生产最大的产品。

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;
}

标签: cfunctionstruct

解决方案


结构成员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`

推荐阅读