0

I tried to use a variable set at runtime to specify the size of a character array,

#include<stdio.h>

int main(void)
{
    int n;
    printf("ENTER THE NUMBER OF Characters IN THE STRING:\n");
    scanf("%d",&n);
    char string[n];
    printf("Enter the string:\n");
    scanf("%s",string);
    printf("\nTHE STRING IS:\n");
    printf("%s\n",string);
    return 0;
}  

I'm not able to understand the following output,

ENTER THE NUMBER OF Characters IN THE STRING:
2
Enter the string:
abcdefghijk

THE STRING IS:
abcdefghijk

Even after specifying the number of characters in the string as 2, why is the whole of the string that is entered being displayed?

3 Answers3

1

Accessing an array index out of bound, invoked undefined behaviour.

C11 Standard:

J.2 Undefined behavor

An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).

Addition or subtraction of a pointer into, or just beyond, an array object and an integer type produces a result that points just beyond the array object and is used as the operand of a unary * operator that is evaluated (6.5.6).

msc
  • 33,420
  • 29
  • 119
  • 214
0

As you are accessing index which is out of the scope of an array you will get undefined behaviour because of ArrayIndexOutOfBound.

In C not checking bounds allows a C program to run faster.

You may prefer

Dynamic Memory allocation

Mr. Roshan
  • 1,777
  • 13
  • 33
0

If you are accessing array elements out of bound, it invokes undefined behavior. As C doesn't check array boundary condition, compiler won't throw error but it invokes undefined behavior.

Even after specifying the number of characters in the string as 2, why is the whole of the string that is entered being displayed? It's a programmer job is to ensure there is enough memory space to store data at runtime and handle such things accordingly.

Achal
  • 11,821
  • 2
  • 15
  • 37