I am not sure why I am not getting a display on the console for the value of maxProd. I think I am declaring the arr_integer array variable wrong in main?
I ran a couple tests and the program looks like it does not even get to call solution().
Any help would be greatly appreciated. I am trying to get this to work and get rid of the following warnings;
Adjacent_Element_Product.c:31:40: note: (near initialization for 'array')
Adjacent_Element_Product.c:31:43: warning: excess elements in struct initializer
#include <stdio.h>
typedef struct arr_integer {
int size;
int *arr;
} arr_integer;
arr_integer alloc_arr_integer(int len) {
arr_integer a = {len, len > 0 ? malloc(sizeof(int) * len) : NULL};
return a;
}
int solution(arr_integer inputArray) {
int maxProd = inputArray.arr[0] * inputArray.arr[1];
for (int i = 1; i < inputArray.size - 1; i )
{
int product = inputArray.arr[i] * inputArray.arr[i 1]; //multiple next door neighbours.
if (product > maxProd)
maxProd = product;
}
return printf("maxProd: %d\n", maxProd);
}
int main()
{
arr_integer array = {3, 6, -2, -5, 7, 3};
solution(array);
return 0;
}
CodePudding user response:
The problem is that you don't allocate memory for the array and that it then tries to use the list of integers as an int*
.
A possible remedy:
#define Size(x) (sizeof (x) / sizeof *(x))
int main() {
int ints[] = {3, 6, -2, -5, 7, 3};
arr_integer array = {.size = Size(ints), .arr = ints};
solution(array);
}
CodePudding user response:
Here are the relevant changes:
- added <stdlib.h> for
malloc
- eliminated
alloc_arr_integer()
which was not used maxProd
is initialized toINT_MIN
and tweaked initial loop condition to reduce duplication- to make the solution a little smaller passing the value inline to solution (@TedLyngmo probably gave you a better solution)
Not fixed:
arr_integer
doesn't seem to add any value so maybe just pass size and array tosolution()
. You could create a macro to initialize it using the approach @TedLyngmo shared with you. It has to be a macro asint []
degrades toint *
in a function call, and the latter (silently?) gives you the wrong result which makes it error prune.- Does negative size make sense? If not then use an unsigned type.
- What is the solution if
size < 2
? solution()
returns the value fromprintf()
which is strange. You might want to returnmaxProd
and havemain()
print out the value. This makes your function testable
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct arr_integer {
int size;
int *arr;
} arr_integer;
int solution(arr_integer inputArray) {
int maxProd = INT_MIN; // what is answer if size < 2? error?
for (int i = 0; i < inputArray.size - 1; i ) {
int product = inputArray.arr[i] * inputArray.arr[i 1]; //multiple next door neighbours.
if (product > maxProd)
maxProd = product;
}
return printf("maxProd: %d\n", maxProd);
}
int main() {
solution((arr_integer) {
6,
(int []) { 3, 6, -2, -5, 7, 3 }
});
return 0;
}
and the output is:
maxProd: 21