File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes General Computing and the fly likes C question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Engineering » General Computing
Reply Bookmark "C question" Watch "C question" New topic
Author

C question

Thomas White
Ranch Hand

Joined: Feb 01, 2003
Posts: 32
Hello,
I have a C question(I know, what am I doing asking this on javaranch :roll: ) but anyways... The following code is supposed to
read 20 numbers from the console and store them in an int array. However, after the 20th number is read, I get a seg fault. As far as I can see, I'm not writing beyond the array size. What am I doing wrong?
code:
Tom
[ July 25, 2003: Message edited by: Thomas White ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 23395

Well, I don't quite understand the logic of the compare-and-print part; in particular, I don't understand the initializer of the inner loop, the j += i part. The variable j is never really initialized. The first j+=i executes when j contains random stack garbage. So here's one possibility: j is negative. The j+=i gives the same negative number (i is 0) and so you access a value before the beginning of the array; this could be an illegal address, giving you the seg fault.


[Jess in Action][AskingGoodQuestions]
Thomas White
Ranch Hand

Joined: Feb 01, 2003
Posts: 32
Ernest,
Thanks for pointing that out. I meant to write j = i + 1. Now its working.
Thanks again.
Thomas
Gregg Bolinger
Sheriff

Joined: Jul 11, 2001
Posts: 15040

Thomas, just an FYI, a good place for C questions - http://forums.embeddedthought.com


My Blog | DZone Articles
 
IntelliJ Java IDE
 
subject: C question
 
Threads others viewed
Problem in C
How do the values change even if I am not passing the arrays with reference?
How to input user values multi-dimensional arrays
How to use EL to get the value
How to shrink/grow lines
IntelliJ Java IDE

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture