Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SImple C program with array is not printing proper output

Tags:

c

gcc

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?

like image 701
Torsten Hĕrculĕ Cärlemän Avatar asked Aug 30 '26 22:08

Torsten Hĕrculĕ Cärlemän


1 Answers

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);
}
like image 98
Carl Norum Avatar answered Sep 01 '26 11:09

Carl Norum