Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Program not entering for loop, but incrementing loop index variable?

Here is the COMPLETE text of my program, besides what has been commented out:

#include <stdio.h>



int main (int argc, char* argv[] ){

   FILE* inFile = fopen(argv[1], "r");

   if(inFile==0){
      printf( "Error opening file, terminating program\n");
      return 1;
      }

   char* charArray = malloc(100*sizeof(char));

   int j=0;

   printf("%i", j);


   for(j=0; j++; j<100){
      printf("%c", charArray[j]);
      printf("%c", '\n');
      }


   printf("%i", j);

   return 0;
   }

I will call my program with the parameter text which is the name of a text file I want it to open. The part of my program that is commented out reads the text file into a character array, the same array I am trying to print in the for loop.

Right now, the char array contains complete garbage, but that's not the point--the point is, it's not outputting ANYTHING when it should at least be outputting SOMETHING!

Here is the output I am getting:

01

Somehow, j is being incremented exactly once, but I'm not even getting any endlines printed from within the for loop. What is going on?

like image 455
Bobazonski Avatar asked Aug 17 '26 21:08

Bobazonski


2 Answers

Your loop formatting is wrong.

The format for a for loop is:

for(INITIALIZATION; CONDITION; INCREMENT/DECREMENT){

}

You have the CONDITION and INCREMENT/DECREMENT mixed up

Change:

for(j=0; j++; j<100)

To:

for(j=0; j<100; j++)
like image 107
nem035 Avatar answered Aug 20 '26 19:08

nem035


change

for(j=0; j++; j<100)

to

for(j=0; j<100; j++)
like image 40
chouaib Avatar answered Aug 20 '26 18:08

chouaib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!