• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Let's assume that the node's actual load is sensitive information that cannot be exposed outside the node itself, but the average is not sensitive.

With your approach, some external code or eavesdropper could always determine the value of the node's load exactly just by multiplying by 2. However there are ways to compute the average without disclosing the exact value of a single node. Basically, you want to construct two mathematical functions, f & g, such that

g(f(load1), f(load2)) = (load1 + load2)/2

AND

f^-1(x), the function inverse, is difficult or impossible to compute.

I'm about to be late for a meeting, so I don't have time to explain this step by step, but basically you can keep a synchronized random number generator inside the node class, and use it to introduce a random element into f() that will not be known by the outside.

If you can't figure out a mathematical function to use, then make two different f() functions, and have one be e1 = (load1 + random) and the other be e2 = (load2 - random), then your average is (e1 + e2)/2, but the outside world can't figure out load1 or load2 without knowing the value of 'random'.

That makes sense, thanks!

It sounds to me like the instructor wants you to access the load indirectly, to demonstrate encapsulation.

Yeah, that's what I thought of at first too, but the wording was that the value of __load can never leave the object. Accessing it with a getter would mean that the value was still leaving the object...I think tokkun's explanation was likely what the instructor was getting at, because the "real world" example the instructor stated in the problem was computing the average sum from a set of bank accounts. In the example every account was a "Node", and doing this would prevent you from ever having to transfer the exact amount over the network.
 
What course/course level is this in if you don't mind me asking?

It's a Python/Perl class. (A "3000" level course, if that means anything -- generally taken by Sophomores or Juniors.) It's been a pretty easy class, since I think the purpose has mainly been to introduce CS students here to dynamically typed scripting languages, since most of the other courses focus on C++ or Java.

This question surprised me a bit, because it's been the only one the entire semester that wasn't trivially easy. At first it did just seem like encapsulation to me (and to show a bit of how Python uses name mangling rather than actually allowing private class members, given the __load name). But the wording really makes me think I should be leaning more towards tokkun's suggestion.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
It's a Python/Perl class. (A "3000" level course, if that means anything -- generally taken by Sophomores or Juniors.) It's been a pretty easy class, since I think the purpose has mainly been to introduce CS students here to dynamically typed scripting languages, since most of the other courses focus on C++ or Java.

This question surprised me a bit, because it's been the only one the entire semester that wasn't trivially easy. At first it did just seem like encapsulation to me (and to show a bit of how Python uses name mangling rather than actually allowing private class members, given the __load name). But the wording really makes me think I should be leaning more towards tokkun's suggestion.

That's what I was looking for, thanks.

Also, you mentioned that your other assignments have been really easy. Maybe you are overthinking this one. I would send the professor an email and ask if he intends for you to use encapsulation, or if he is trying to teach you how to use functions.
 

usea

Member
What do you all think of this code (C#) I wrote today (slightly edited):
Code:
private void Main()
{
    var records = ReadAllRecords();
    foreach (var record in records)
    {
        SaveRecord(record);
    }
}

private IEnumerable<string> ReadAllRecords()
{
    return Infinity<int>().Select(x => ReadNextRecord()).TakeWhile(x => x != null);
}

private IEnumerable<T> Infinity<T>()
{
    return new[] { default(T) }.Cycle();
}

public static class Extensions
{
    public static IEnumerable<T> Cycle<T>(this IEnumerable<T> source)
    {
        while (true)
            foreach (var i in source)
                yield return i;
    }
}

ReadNextRecord() either returns the next record, or null if there are no more. Also since it's lazy, it reads one record at a time, then saves it before reading the next one. I prefer this coding style over loops and changing variables. Am I crazy? What do you think of stuff like this?

I left out the braces in the end just to reduce the length in this paste. ReadNextRecord() queries a hardware device over the network which can only return one record at a time, or nothing once you've gotten everything.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I've seen a lot of people write code like yours with the curly braces under the declaration instead of immediately after.

Code:
public static void main(String[] args) 
{
    Code
}

Instead of

Code:
public static void main(String[] args) {
       Code
}

What's the reason for that?
 
I've seen a lot of people write code like yours with the curly braces under the declaration instead of immediately after.

Code:
public static void main(String[] args) 
{
    Code
}

Instead of

Code:
public static void main(String[] args) {
       Code
}

What's the reason for that?

Just personal preference. Some like one way more than the other.
 
I've seen a lot of people write code like yours with the curly braces under the declaration instead of immediately after.

Code:
public static void main(String[] args) 
{
    Code
}

Instead of

Code:
public static void main(String[] args) {
       Code
}

What's the reason for that?

Because it is the superior method

Wars have been waged over less btw.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Am I going to be tarred and feathered if I admit to preferring the in-line bracket?
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
Oh man, braces convention, a tinderbox comparable to vi versus emacs :p

I used to be a braces on new line after declaration person, but I've been trying my hardest to convert to braces after declaration before new line, modern IDE reformatting helps, but the latter still looks unnatural to me :p

To add to that, some conventions confuse me, Google's Java convention for code submission is for "spaces for indentation" instead of "tabs to indent", but their Android convention isn't, baffling!

It could be worse, I remember when the popular Perl convention was "all whitespace must be eliminated at all costs" and "your code must look like an IOCCC submission", man, reading someone elses Perl during those days was headache inducing :p
 

usea

Member
I use same-line braces in most languages since it's the standard in them. But in C# newline braces are the way it's done so I do that. I don't really have a preference except that I'm more used to newline braces. But whatevs.
 

Husker86

Member
New line braces look so funny to me. But I'm a noob programmer and it's probably just because that's how the first tutorials I watched formatted it.
 

Tristam

Member
Slavik/any other Qt users: is it possible to use QDataWidgetMapper() to map widgets to a tree-based model? Since widgets are mapped by integer (column or row, rather than two-dimensional index) based "sections", and the QStandardItemModel resets the row value for child items, without any additional tweaks there will be ruinous overlap between the sections of child and parent widgets. The only tweak I can think of is subclassing QStandardItemModel to entirely change the implementation of index values. Beyond that, I can only think to do updates to the model from widgets manually, but it would be nice if it were possible to utilize the mapper. Below is a full dialog window demonstrating my problem. (You can run if you have either PySide or PyQt installed; if the latter, I think you'll only need to replace PySide with PyQt in the from statements.)


Code:
#!/usr/bin/python
from PySide.QtCore import *
from PySide.QtGui import *
import sys

class Form(QDialog):

	def __init__(self, parent=None):
		super(Form, self).__init__(parent)
		self.setWindowTitle("Test Widget Mapper")
		
		self.model = QStandardItemModel(self)
		self.rootitem = self.model.invisibleRootItem()

		self.treeview = QTreeView()
		self.treeview.setModel(self.model)
		
		self.mapper = QDataWidgetMapper(self)
		self.mapper.setSubmitPolicy(QDataWidgetMapper.AutoSubmit)
		self.mapper.setModel(self.model)
		self.mapper.setOrientation(Qt.Vertical)
		self.mapper.setRootIndex(self.rootitem.index())
		
		# create widgets
		self.line_edit1 = QLineEdit()
		self.line_edit2 = QLineEdit()
		self.line_editsub = QLineEdit()
		
		# create and set layout
		layoutw = QHBoxLayout()
		layout = QVBoxLayout()
		layout.addWidget(QLabel("Item 1:"))
		layout.addWidget(self.line_edit1)
		layout.addWidget(QLabel("Subitem 1:"))
		layout.addWidget(self.line_editsub)
		layout.addWidget(QLabel("Item 2:"))
		layout.addWidget(self.line_edit2)
		layoutw.addWidget(self.treeview)
		layoutw.addLayout(layout)
		self.setLayout(layoutw)
		
		# create and map items
		self.item1 = QStandardItem("Item 1")
		self.item2 = QStandardItem("Item 2")
		self.subitem1 = QStandardItem("Sub item 1")
		self.rootitem.appendRow(self.item1)
		self.item1.appendRow(self.subitem1)
		self.rootitem.appendRow(self.item2)
		self.mapper.addMapping(self.line_edit1, 0)
		self.mapper.addMapping(self.line_edit2, 1)
		self.mapper.toFirst() 
		
		self.treeview.expandAll()

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
 

iapetus

Scary Euro Man
Newline braces let you see at a glance where a block of code started.
Same line braces let you see at a glance why a block of code started.

My preference is always for the latter. But I'll use the former if that's the local standard.
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
I was taught that the reason for using new line braces was their use as 'bookends' to more easily recognize scope, so yeah, I agree with the "where" there iapetus.

You are also right that the right formatting to use is whatever convention is expected/required either by the project you are on, or the employer you are with, personal preference in those domains doesn't really come into it :p
 
The default for C# in Visual Studio is Allman-style, or new line braces. I prefer it, it creates natural white space and makes code blocks stand out. But I can certainly work with other styles as necessary.
 

tokkun

Member
You should try to be efficient in your use of vertical space. It allows more actual code to fit on the screen at once, and this can be beneficial to someone trying to read and understand your code.

Putting the opening brace in-line reduces vertical waste at little cost to readability.
 
You should try to be efficient in your use of vertical space. It allows more actual code to fit on the screen at once, and this can be beneficial to someone trying to read and understand your code.

Putting the opening brace in-line reduces vertical waste at little cost to readability.

Well, that gets into a different discussion, because I want less code on screen, not more. Less code to understand at any given time. I don't want vertical length of code to be a consideration, not if I can help it. Small functions, small classes.
 

tokkun

Member
Well, that gets into a different discussion, because I want less code on screen, not more. Less code to understand at any given time. I don't want vertical length of code to be a consideration, not if I can help it. Small functions, small classes.

Keeping functions and classes small and efficiency of vertical space are separate issues.

The thing about using a new line for opening parentheses is that you sometimes end up with multiple nested loops with if-then-else blocks, and you end up not being able to fit the entire thing on screen at once.
 
I was taught that the reason for using new line braces was their use as 'bookends' to more easily recognize scope, so yeah, I agree with the "where" there iapetus.

You are also right that the right formatting to use is whatever convention is expected/required either by the project you are on, or the employer you are with, personal preference in those domains doesn't really come into it :p

It does when you are the boss ;)

I always favoured new lines for just about everything because the simpler every line is, the better. Seeing as I stopped printing out code in 1994 and have large monitors, I don't think vertical space comes into it either.
 
I just stumbled across this image. If you've ever browsed through programming books you'll appreciate it.
1800328_10100609482005294_524314009_n.jpg

From Unix in a Nutshell
 

iapetus

Scary Euro Man
Well, that gets into a different discussion, because I want less code on screen, not more. Less code to understand at any given time. I don't want vertical length of code to be a consideration, not if I can help it. Small functions, small classes.

So shrink your editor window. If you shrink it enough you can even get to have to scroll to read a single line. Ultimate efficiency!
 

Exuro

Member
Having an issue comparing strings from fgets. I read that it includes the newline character so I've tried putting that into my comparison but it doesn't seem to work. I'm doing something along the lines of...

if(fgets(buff, size, stdin) = NULL)
exit(1);
else if (buff == "quit\n")
exit(1);
else {
do stuff
}

How would I go about this?

edit: nevermind, I just made a temp variable for fgets and set the '\n' to '\0' before the if statement and then used strcmp to compare. For some reason doing str == "quit" still didnt work but the function does.
 
Having an issue comparing strings from fgets. I read that it includes the newline character so I've tried putting that into my comparison but it doesn't seem to work. I'm doing something along the lines of...

if(fgets(buff, size, stdin) = NULL)
exit(1);
else if (buff == "quit\n")
exit(1);
else {
do stuff
}

How would I go about this?

You can't compare strings like that in C, gotta use strcmp(str1, str2). I believe it returns 0 on a match.
 

Slavik81

Member
Slavik/any other Qt users: is it possible to use QDataWidgetMapper() to map widgets to a tree-based model? Since widgets are mapped by integer (column or row, rather than two-dimensional index) based "sections", and the QStandardItemModel resets the row value for child items, without any additional tweaks there will be ruinous overlap between the sections of child and parent widgets. The only tweak I can think of is subclassing QStandardItemModel to entirely change the implementation of index values. Beyond that, I can only think to do updates to the model from widgets manually, but it would be nice if it were possible to utilize the mapper. Below is a full dialog window demonstrating my problem. (You can run if you have either PySide or PyQt installed; if the latter, I think you'll only need to replace PySide with PyQt in the from statements.)


Code:
#!/usr/bin/python
from PySide.QtCore import *
from PySide.QtGui import *
import sys

class Form(QDialog):

	def __init__(self, parent=None):
		super(Form, self).__init__(parent)
		self.setWindowTitle("Test Widget Mapper")
		
		self.model = QStandardItemModel(self)
		self.rootitem = self.model.invisibleRootItem()

		self.treeview = QTreeView()
		self.treeview.setModel(self.model)
		
		self.mapper = QDataWidgetMapper(self)
		self.mapper.setSubmitPolicy(QDataWidgetMapper.AutoSubmit)
		self.mapper.setModel(self.model)
		self.mapper.setOrientation(Qt.Vertical)
		self.mapper.setRootIndex(self.rootitem.index())
		
		# create widgets
		self.line_edit1 = QLineEdit()
		self.line_edit2 = QLineEdit()
		self.line_editsub = QLineEdit()
		
		# create and set layout
		layoutw = QHBoxLayout()
		layout = QVBoxLayout()
		layout.addWidget(QLabel("Item 1:"))
		layout.addWidget(self.line_edit1)
		layout.addWidget(QLabel("Subitem 1:"))
		layout.addWidget(self.line_editsub)
		layout.addWidget(QLabel("Item 2:"))
		layout.addWidget(self.line_edit2)
		layoutw.addWidget(self.treeview)
		layoutw.addLayout(layout)
		self.setLayout(layoutw)
		
		# create and map items
		self.item1 = QStandardItem("Item 1")
		self.item2 = QStandardItem("Item 2")
		self.subitem1 = QStandardItem("Sub item 1")
		self.rootitem.appendRow(self.item1)
		self.item1.appendRow(self.subitem1)
		self.rootitem.appendRow(self.item2)
		self.mapper.addMapping(self.line_edit1, 0)
		self.mapper.addMapping(self.line_edit2, 1)
		self.mapper.toFirst() 
		
		self.treeview.expandAll()

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
On second thought, I'll wait until I can take a closer look over your code before responding.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I have a Java / swing question for you guys.
My professor gave us an assignment to focus on using multiple classes for GUI display.

The main objective is:
  • Produce a GUI to accept three textfield inputs.
  • After a button press, invoke an instance of a class (Dog).
  • Utilize methods within Dog class to pull data from textfields and display it in a textarea.
Well I have the program working where it can pull the data within itself and display, but I can't figure out how to manipulate the textfields and the textarea from outside of the class they are defined in.
I would appreciate some guidance without outright solving this problem for me, and if you would like me to post code I can. (I avoided it at first since I didn't want to spam ~100 lines.)

Thanks
 

Water

Member
I would appreciate some guidance without outright solving this problem for me, and if you would like me to post code I can. (I avoided it at first since I didn't want to spam ~100 lines.)
You don't spam ~100 lines, you paste into Pastebin and post the link.
 

injurai

Banned
really learning the guts of c now in my operating systems class

forget about pointers

the power of c is in system calls, forking and semaphores.
 

Exuro

Member
Anyone familiar with building a shell(unix)? I'm making a basic one and right now and a little stuck at figuring out how to implement redirection like >, < and whatnot. Right now my command gets parsed into a linked list and I'll(haven't implemented yet, still thinking about it) search for redirection characters like the ones above and pass the values of the list before said char into an array and run exec. This should "work" but I'm having trouble understanding how to redirect from there or if this is how I should go about running a command in the first place.

I'm also having trouble figuring out how to put a process into the background. Any tips/links for either/both of these topics would be great.
 
Anyone familiar with building a shell(unix)? I'm making a basic one and right now and a little stuck at figuring out how to implement redirection like >, < and whatnot. Right now my command gets parsed into a linked list and I'll(haven't implemented yet, still thinking about it) search for redirection characters like the ones above and pass the values of the list before said char into an array and run exec. This should "work" but I'm having trouble understanding how to redirect from there or if this is how I should go about running a command in the first place.

I'm also having trouble figuring out how to put a process into the background. Any tips/links for either/both of these topics would be great.

You'll need to use fork and pipes. You create a pipe, and then fork the process. You execute the command in the child process. You'll also need to check if there's any redirection with the commands you are running -- if so, you use dup2 to duplicate stdout or stdin onto your pipe.

So, for example, if you had this command:

wc < test.txt

In your child process you would see that you need to dup stdin onto test.txt's file descriptor. So you open the file, and use dup2 on that file descriptor. Now, wc will get it's input from test.txt.

It gets more complex when you also need to handle arbitrarily piping between N number of commands. (e.g., "ls | uniq | sort > results.txt"). You also have to make sure you're closing ends of the pipe that you're not using.

This should help out:

http://www.tldp.org/LDP/lpg/node9.html

Once you understand what happens when fork a process and how pipes work, it's pretty simple. So I would read up on those, and then it should hopefully fall into place. Just remember that when you fork something it creates a copy of the ENTIRE process control block, which is different from a thread, which is running on the same process and shares memory. That means you need a way to communicate between the two processes, which is where the pipes come into play. Pipes have a read and a write end, and can communicate between processes.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I was able to solve the problem by creating a static String variable to store the information.

Then I modified the variable from the outside class by pulling the information from textfields and add it to the string.

I'm sure it's not the most efficient way to go about this problem, but here's the modified code
 

iapetus

Scary Euro Man
I was able to solve the problem by creating a static String variable to store the information.

Then I modified the variable from the outside class by pulling the information from textfields and add it to the string.

I'm sure it's not the most efficient way to go about this problem, but here's the modified code

That's not inefficient. That's horribly, horribly, horribly, horribly wrong.

Every time you *create* a Dog using this it's setting that value. After that the dogs are useless. This really isn't what you're supposed to be doing. Try rethinking things so that you actually use a Dog instance to provide the data to the UI. Stay away from static variables for this, and stay away from directly modifying fields of the UI classes from your data classes.

If I get time later I'll take a look at the history of this and see if I can point you in the right direction.
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
Sounds like a observer pattern case to me, there are plenty of examples around of this pattern being used specifically for this problem, inter-object communication / callbacks especially with Java user interface elements.
 
Working on some basic 2d collision detection for an assignment and I guess I was a little lazy with floats but I was running into this weird bug when adjusting the x,y coordinates. I wasn't being precise enough so when I was checking the bounding box it would bug out because the number was something like X.00000001 for some reason and I was checking for X.00. *sigh* ThankfullyI didn't spend too much time on that..
 

usea

Member
Working on some basic 2d collision detection for an assignment and I guess I was a little lazy with floats but I was running into this weird bug when adjusting the x,y coordinates. I wasn't being precise enough so when I was checking the bounding box it would bug out because the number was something like X.00000001 for some reason and I was checking for X.00. *sigh* ThankfullyI didn't spend too much time on that..
Often with floats it makes a lot more sense to check a difference rather than equality. Have some very small epsilon value which you consider to be "close enough to the same", then subtract your floats and see if the difference is within the epsilon from zero.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
That's not inefficient. That's horribly, horribly, horribly, horribly wrong.

Every time you *create* a Dog using this it's setting that value. After that the dogs are useless. This really isn't what you're supposed to be doing. Try rethinking things so that you actually use a Dog instance to provide the data to the UI. Stay away from static variables for this, and stay away from directly modifying fields of the UI classes from your data classes.

If I get time later I'll take a look at the history of this and see if I can point you in the right direction.

Well I look forward to learning what the correct way to do this is if you have the time.
The assignment was asking for the textarea to be changed by utilizing the Dog class, but I think I misunderstood what he meant. My next assignment will be using the same concept, except adding data into a 2D array before displaying it, so I'd like to learn the correct way for object communications.

Osiris, I'm going to look into the Observer pattern you mentioned. Thank you.
 
Working on some basic 2d collision detection for an assignment and I guess I was a little lazy with floats but I was running into this weird bug when adjusting the x,y coordinates. I wasn't being precise enough so when I was checking the bounding box it would bug out because the number was something like X.00000001 for some reason and I was checking for X.00. *sigh* ThankfullyI didn't spend too much time on that..

Yep, floating point equality is hard. Here is a good article on that subject. There's a whole series on floating point numbers on that blog as well.
 

hateradio

The Most Dangerous Yes Man
Well I look forward to learning what the correct way to do this is if you have the time.
The assignment was asking for the textarea to be changed by utilizing the Dog class, but I think I misunderstood what he meant. My next assignment will be using the same concept, except adding data into a 2D array before displaying it, so I'd like to learn the correct way for object communications.

Osiris, I'm going to look into the Observer pattern you mentioned. Thank you.
What you're doing now with the Dog class is pretty useless since it really just changes the frame's display value. You're not really doing anything with the dog, in other words.

You should create a dog along with useful properties.

Code:
class Dog
{
	String name;
	String breed;
	String age; // Maybe use an int instead
	
	Dog(String name, String breed, String age)
	{
		this.name = name;
		// etc
	}
}

// later you can use it to create a Dog

myDog = new Dog("Doggy", "Doggy breed", "1");

System.out.println(myDog.name) // "Doggy"
System.out.println(myDog.breed) // "Doggy breed"
System.out.println(myDog.age) // 1

Note: I didn't use setters or getters since I'm not sure if you're at that stage in your class.


Finally, in your frame class you can create a method that updates its display after it receives a Dog.

Code:
public void displayDog(Dog dog)
{
	this.display = " Name: " + dog.name; //eg
}
 

Gartooth

Member
I'm currently building a project in C where the objective is to allocate memory for an array of nodes that is created from words read from a text file. Nodes contain text (a word read from the text file) and a pointer to another node. In a sense, each element in the array acts as its own linked list. The program is supposed to add new words with no anagrams to the next spot in the array (ex: list[0], list[1], etc.), but if that word is an anagram with any existing elements in the array, then it should be added to its counterparts linked list via "next". (ex: an anagram for list[0] would be list[0]->next)

However, the program keeps generating segmentation faults when building the list and tracking it down has been a giant pain. The current program for building is:
Edit: Issue fixed.
 
Often with floats it makes a lot more sense to check a difference rather than equality. Have some very small epsilon value which you consider to be "close enough to the same", then subtract your floats and see if the difference is within the epsilon from zero.

Yeah I started doing that. The annoying thing was it was only happening in like 2 of my test cases so... meh.

Yep, floating point equality is hard. Here is a good article on that subject. There's a whole series on floating point numbers on that blog as well.

Thanks for that.

I'm currently building a project in C where the objective is to allocate memory for an array of nodes that is created from words read from a text file. Nodes contain text (a word read from the text file) and a pointer to another node. In a sense, each element in the array acts as its own linked list. The program is supposed to add new words with no anagrams to the next spot in the array (ex: list[0], list[1], etc.), but if that word is an anagram with any existing elements in the array, then it should be added to its counterparts linked list via "next". (ex: an anagram for list[0] would be list[0]->next)

However, the program keeps generating segmentation faults when building the list and tracking it down has been a giant pain. The current program for building is:

snipity snip

I don't think you're allocating space for the individual lists inside the array. You only allocate the space for the array but each index outside of 0 is not allocated.
 

tokkun

Member
Code:
	list = (Node **) calloc(*arySize, sizeof(Node *)); //allocates memory for list

	while(fgets(text, MAX_WORD_SIZE, fp) != NULL){ //reads word from text file
		text[strlen(text)-1] = '\0';
		int i;
		for(i = 0; i < *arySize; i++){
			if(areAnagrams(list[i]->text,text)){

You are filling list with a bunch of null pointers with your calloc statement.

Then you try to dereference list, which causes a segmentation fault.

Probably your for loop should terminate when list == NULL.
 

Gartooth

Member
I don't think you're allocating space for the individual lists inside the array. You only allocate the space for the array but each index outside of 0 is not allocated.

You are filling list with a bunch of null pointers with your calloc statement.

Then you try to dereference list, which causes a segmentation fault.

Probably your for loop should terminate when list == NULL.


Thanks for the replies. I guess I'm a bit confused then on how to go about solving this. Is calloc itself just setting aside memory for the list, but I never actually "made" the list? Also, in terms of dereferencing list, how would I go about getting the text information from each node if my current approach is causing segmentation faults?

I suppose I'm just stumped at this point, this is my first time using this kind of memory allocation in C so I appreciate the help.

Edit: Also, this wasn't listed in my original code post, but the helper function createNode will use a malloc for both the node itself as well as the text field for the node.
 

Hylian7

Member
This is going to seem like a stupid question, and I can't seem to get a straight answer by Googling it. I'm writing a Java application that's basically a Dota 2 Drafting game for a bit of premise on what I'm trying to do here.

Basically I need to get the pictures (which I have saved in a directory) of all the characters to put on the buttons, but I keep getting an IIOException. Here's what's causing it.

Code:
for (int i = 0; i < heroes.size(); i++) {
			h = heroes.get(i);
			String filename = "C:/Users/Matt/Documents/GitHub/Dota2DraftingGameDesktop/src/Assets/" + h.getImage();
			[B]BufferedImage buttonIcon = ImageIO.read(new File(filename));[/B]
			JButton button = new JButton(new ImageIcon(buttonIcon));
//Other stuff
} //End of for loop

I bolded the specific line that's causing the exception and I cannot for the life of me figure out what the issue is.

Now I tried this just to see if it would work. Obviously this isn't the way I want to do it, but strangely, it DID work.

Code:
for (int i = 0; i < heroes.size(); i++) {
			h = heroes.get(i);
			String filename = "C:/Users/Matt/Documents/GitHub/Dota2DraftingGameDesktop/src/Assets/axe.png";
			BufferedImage buttonIcon = ImageIO.read(new File(filename));
			JButton button = new JButton(new ImageIcon(buttonIcon));
//Other stuff
} //End of for loop

Obviously, this would have all the buttons have the same hero picture on them, which is what I was trying for testing purposes. Now why the hell won't the top method work?

Well I googled it a bit, found a few StackExchange questions on the issue, and none of them really seemed to answer the question. Some of them think it is a bug in Eclipse, as they tried other IDEs/running it from cmd and it worked just fine.

Edit: Let me preemptively answer that getImage() does in fact return a string, so that's not the issue either.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
What happens if you create a new variable to store the value from
Code:
h.get image()

then concatenate that variable to the end of your filename instead of using the h.get image().
 
Top Bottom