-2

I want to know how I can catch IndexOutofbounds in C. I do not want my program to exit abnormally, I want to print a message for the user that clarify the error

how I can check for this case

 char a[50];
 fgets(a,200,stdin);

I need to exit the program and throw an error,and I do not need to change the 200 to use sizeof()

  • 1
    There are no exceptions to catch in C! – Graeme Sep 22 '19 at 18:43
  • 3
    By comparing the index with the array length? – Weather Vane Sep 22 '19 at 18:44
  • Easy. Switch to Java. – klutt Sep 22 '19 at 19:08
  • It's all very well catching an error during development and debugging, but most commercial code will be a failure if it only makes for a more polite and informative emergency exit. There really needs to be a recovery strategy, for example producing a list of absurd data that could not be processed, or requesting that an out-of-range input be re-input, and so on. – Weather Vane Sep 22 '19 at 19:30

2 Answers2

3

This is one of those things you simply cannot do in C. At least not without a lot of hazzle. You will have to keep track of such things yourself. So when you declare an array, then you will have to store the size and do something like this:

size_t size=1000;
int arr[size];
...
if(i>=size || i<0) {
    // Handle error
} else {
    // Do something with arr[i]
}

You can make abstractions and make it more Java-like with constructs like this:

struct array {
    int *val;
    size_t size;
};

int getVal(struct array array, size_t index) {
    if(index>=array.size || index<0) 
        // Handle error
    else
        return array.val[index];
}

But if you are using constructs like that, chances are high that it might me a good idea to switch to another language instead.

If we look at your particular example:

char a[50];
fgets(a,200,stdin); 

I'm sorry to say it, but it is impossible to make fgets throw an error in this situation.

klutt
  • 30,332
  • 17
  • 55
  • 95
0

First of all, C doesn’t have a structured exception handling mechanism. There’s no try...catch control structure in C (there is in C++ and C#, but those are different languages).

Secondly, C doesn’t do any bounds checking on array accesses - you, the programmer, are expected to do those checks yourself.

John Bode
  • 119,563
  • 19
  • 122
  • 198