I am new to C arrays and I am facing a problem that my code returns an error of invalid memory access.
Here is the exact error:
"Caught unexpected signal: SIGSEGV (11). Invalid memory access."
Here is my code:
#include <stddef.h>
int factorial(int x) {
if (x == 0 || x == 1) {
return 1;
}
else {
return x * factorial(x - 1);
}
}
unsigned long long sum_factorial(size_t z, const int array[z]) {
unsigned long long result = 0;
for (size_t i = 0; i < z; ++i) {
result = result + factorial(array[z]);
}
return result;
}
>Solution :
**small mistake in above code please replace array[z] with array[i] inside for loop ** Below I mentioned correct code please refer it.
#include <stddef.h>
int factorial(int x) {
if (x == 0 || x == 1) {
return 1;
} else {
return x * factorial(x - 1);
}
}
unsigned long long sum_factorial(size_t z, const int array[z]) {
unsigned long long result = 0;
for (size_t i = 0; i < z; ++i) {
result = result + factorial(array[i]); // error fix in here,
}
return result;
}