Array Bounds Validator
C
Medium
3 views
Problem Description
Create a function that accesses the array. Validate the index parameter - if out of bounds return error, allow valid access.
Official Solution
#include <stdio.h>
int get_element(const int arr[], int size, int index, int *value) {
// Validate index
if (index < 0 || index >= size) {
return -1; // error: out of bounds
}
*value = arr[index];
return 0; // success
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
int value;
int index;
int status;
printf("Enter index: ");
scanf("%d", &index);
status = get_element(arr, size, index, &value);
if (status == 0) {
printf("Value at index %d = %dn", index, value);
} else {
printf("Error: Index out of bounds!n");
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!