Responsive Advertisement

Adding and Printing elements of an array in C

 Adding and Printing elements of an array in C



The problem seems to be here:

This loop always executes 200 times regardless of what is in the file. In other words - the value of howManyItems will be 200 when the loop is done.

You can check that simply by printing howManyItems after the loop, i.e.

Since you have:

then

will write outside of the array. That is undefined behavior.

You need to stop the first loop once the whole file has been read. Something like:

and all the following loops must then use howManyItems as the upper limit.

Like

BTW: Since you want to be able to add 4 extra chars, you probably should do:

BTW: Hard-coding the value 200 over and over again is bad practice. Instead use a define like:

and replace all the hard-coded 200 with MAX_CHARS. Then you can adjust the maximum simply by editing one line instead of multiple lines.

Post a Comment

0 Comments