Printing Arrays in C

I'm only building C right now, so I'm pretty terrible since I'm coming from basic Python. I am trying to print elements in an array using for-loop, but this does not match the correct path.

#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 conclusion

 134513952 

I don’t know why to print it.

+4
source share
3 answers

You have an extra semicolon.

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

This semicolon means that your for loop has an empty body, and you end printing after the loop ends, equivalently:

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

Since this value goes beyond the array, you get undefined behavior and some weird output.

Editorial note. You should study the compiler that gives the best warnings. Clang , for example, gives this warning, even without special flags:

 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 
+7
source

Skip sliders in a for loop:

 for (i=0;i<5;i++); 

For your logic, you don't need a sym-colon after a for loop.

Due to the semi-colony, the for-loop is evaluated 5 times, and by the time printf reached, the value of i is 5. Now, trying to access index 5 in the array gives you an unknown value, since you initialized the array with only 5 values. This may become clearer if you were to print the value of i in the printf statement:

  for (i=0;i<5;i++); { printf("i: %d \t Val: %d",i, array[i]); } 

Gives you the result, for example:

 i: 5 Val: 32767 
+2
source

The semicolon after the loop was a problem. Before any random number was printed, since the storage class was automatic.

 #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"); } 
0
source

Source: https://habr.com/ru/post/1502930/


All Articles