简体   繁体   中英

SImple C program with array is not printing proper output

I wrote this incredibly stupid code

#include <stdio.h>
main(){
    int new[10], i;
    for(i=1; i<=10; ++i){
            new[i] = 0;
            }

for(i=1;i<=10; ++i)
            {
                    printf("%d", new[i]);
            }
 }

I compiled this using GCC on Xubuntu and then did the ./a.out. The cursor is just blinking resulting in no output. The same is the case when tried to debug with gdb. It runs and then stays with the blinking cursor.

Any help?

C arrays are 0 indexed - your program writes outside the boundaries of the new array, so it causes undefined behaviour. In this case, you probably are overwriting the i variable, so you end up with an infinite loop. You need to change your loops:

for (i = 0; i < 10; i++)
{
    new[i] = 0;
}

and:

for (i = 0; i < 10; i++)
{
    printf("%d", i);
}

you need to have a new line character to see the output , or flush the stdout otherwise sometimes it doesn't print, or it will be combined with the next line... try:

printf("%d\n", new[i]);

also, set your for loop from 0 to 9

int new[10] - Here new array can store 10 elements of type integer. You can access these elements from 0th to 9th index of array. Accessing beyond 9th index is undefined behavior.

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