Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing arrays in C

Tags:

arrays

c

printing

I'm just now picking up C, so I'm pretty terrible since I'm coming from basic Python. I'm trying to print the elements in an array using a for-loop, but it's not coming out the right way.

#include <stdio.h>
#include <math.h>
int main()
{
  int array[]={0,1,2,3,4};
  int i;
  for (i=0;i<5;i++);
  {
      printf("%d",array[i]);
  }
  printf("\n");
}

My output is

134513952

I have no clue why it's printing this.

like image 649
Anthony Devoz Avatar asked Jan 12 '23 08:01

Anthony Devoz


1 Answers

You have an extra semicolon.

 for (i=0;i<5;i++);
                  ^
                  |
        here -----+

That semicolon means your for loop has an empty body, and you end up printing after the loop completes, equivalently:

printf("%d", array[5]);

Since that value is beyond the end of the array, you get undefined behaviour and some strange output.

Editorial note: You should look into a compiler that gives better warnings. Clang, for example, gives this warning, even with no special flags passed:

example.c:7:20: warning: for loop has empty body [-Wempty-body]
  for (i=0;i<5;i++);
                   ^
example.c:7:20: note: put the semicolon on a separate line to silence this
      warning
like image 113
Carl Norum Avatar answered Jan 21 '23 23:01

Carl Norum