C help needed! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

C help needed!

Hey guys! I am having a little problem with a C program. I was writing a program to look through an array of numbers to see if a pair existed and it works except for one small issue... If you ask it for a sum where one of the addends is the number at the 0 index it doesn't recognize it as a pair that equals the sum for some reason. I printed out the contents of addend 1 and 2 and there appears to be some kind of garbage at that position in the index for some reason. https://code.sololearn.com/cb1m80V20CO3/?ref=app

16th Jun 2018, 12:22 AM
Haon1919
Haon1919 - avatar
3 Answers
+ 3
You only allocated a single character to read your input string so it over wrote your other data. Change char inputSum; to char inputSum[20];
16th Jun 2018, 4:06 AM
John Wells
John Wells - avatar
+ 2
You stated you have 4 characters allocated for the input due to sizeof(int). Since you only had one, typing anything was going to overwrite something. fgets reads a string so say you enter 14 at the prompt. It would be 3 characters because strings end with a '\0' character. Your sizeof(int) parameter should be changed to sizeof(inputSum).
16th Jun 2018, 4:30 AM
John Wells
John Wells - avatar
+ 1
Hey it worked! Thank you! So if im understanding what your saying correctly, the issue was that I was trying to read an integer into a char and I was experiencing some overflow because I did not have enough memory allocated to hold a value of size int?
16th Jun 2018, 4:14 AM
Haon1919
Haon1919 - avatar