c - 结构体函数的传递和返回

标签 c function 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;
}

最佳答案

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

相关文章:

c - 从一个位置打印到另一个位置 - 使用 printf

c++ - 在 C++ 中使用 min 和 max 函数

c - 为什么在分配最大单点浮点值时出现错误 "integer literal is too large to be represented in any integer type"?

go - 在 Golang 中复制非空结构值以更新数据存储

c - 如何在 Windows 上用 C 语言从另一个程序启动一个独立的程序(在单独的控制台窗口中)?

function - 由于 NanoMatch 问题,Firestore 的 Firebase 功能失败

swift - 在一行中找到重复的序列

c++ - c++中的函数指针赋值和调用?

c - 我可以假设结构字段按顺序放置并且没有填充吗?

c++ - 在结构数组上使用 C++ std::copy