简体   繁体   中英

Why with base index 1 C program works fine?

This may be a naive question but as per my understanding I know that by deafult base index of an array starts with zero. What I don't understand is that why the following program working fine when used base 1 indexing.

#include<stdio.h>
int main()
{
    int n;
    scanf("%d",&n);
    int a[n];
    int i;
    for(i=1;i<=n;i++)
        scanf("%d",&a[i]);
    printf("%d",a[n]);
    return 0;
}

What I don't understand is that why the following program working fine

it's just bad luck.

This is undefined behaviour. That means the compiler doesn't have to warn you, and no code is emitted to check it at runtime.

Undefined means completely undefined, which includes working , and appearing to work until after you ship it to a customer , as well as the more obvious locking up your machine, formatting all the disks and setting fire to your PSU .

Your code will compile but you won't get expected results.
First element of array a will not be printed and one garbage value will be printed at end of array as there is no bound checking for arrays in c.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM