2

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?

8
  • 3
    Don't use new for variable names - it's a keyword. Commented Jul 23, 2013 at 17:02
  • 4
    new is not a keyword in C. Commented Jul 23, 2013 at 17:02
  • Could've sworn this question was titled C++ a second ago... Commented Jul 23, 2013 at 17:05
  • I don't see any edits. Commented Jul 23, 2013 at 17:05
  • new is not a keyword in c, but in this era it is probably better to avoid using it as a identifier in new (heh!) code, simply because so many c programmers also write c++ and so much c code gets included into c++ projects. Commented Jul 23, 2013 at 17:05

3 Answers 3

9

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Hi! It worked! Could you tell me why I didn't encounter the error in MinGW?
Undefined behaviour is undefined. Anything could happen, including the possibility of correct-looking behaviour.
Thanks anyway! I went paranoid when it didn't print anything.
@AnuragPallaprolu The c compiler never promises to detect programer intent. You are assumed to know what you are doing and to say what you mean; if you ask for something strange (or even stupid) the compiler will generally give it to you.
@dmckee I assume it is very generous :)
1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.