Hello Again!
On this Super Bowl Sunday, I am working through some problems in my C book. This post is about writing a function that returns the largest element in an array.
When running my program, I get memory issues at greater array lengths. For example, choose array length of "5" and the elements of the array as "1 100 3 4 5": the output is correct, namely that the largest element is "100", but then the program also crashes with "error: memory read failed for 0x7fff000000002."
I'd like to know two things: 1) What is wrong with my code? and 2) What does this memory failure mean?
Code pasted below. Thank you all for your help!
Code:
#include <stdio.h>
int largest_element(int n, int a[n]);
int main(){
int b[] = {0}, i, z;
printf("Enter the length of the array: ");
scanf("%d", &z);
printf("Enter the values of the array: ");
for (i = 0; i < z; i++){
scanf("%d", &b[i]);
}
largest_element(z, b);
return 0;
}
int largest_element(int n, int a[n]){
int hi = 0, i;
for (i = 0; i < n; i++){
if (a[i] > hi){
hi = a[i];
}
}
return printf("The largest element is %d\n", hi);
}