• 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

Chris R

Member
So does anyone have a suggestion for a hosting solution? I'd prefer for it to be ASP.Net/SQL Server compliant but if it isn't then I guess that will just kinda push me into learning other stuff sooner. Looking at 1&1 for now but if there is something better let me know!

And what is the general consensus on getting further degrees when it comes to CS? Would something like a MBA be good for me in the long run as I evolve from a code monkey into a project manager/division leader/CTO type positions (hopefully)?
 

Godslay

Banned
Just went on Reddit and found alot of resources, tips, etc. Definitely recommend checking that site. There's even a reddit for daily programming challenges.

I frequent /r/learnprogramming, /r/programming, /r/python, and /r/csharp. I've also participated in the daily challenges. Reddit has a ton of programmers, developers from what I've noticed.
 

usea

Member
What's a good, free, source control/defect tracker/document management combination? Bonus points for VS integration.
We use Kiln/Fogbugz by Fog Creek, but we pay for it. I don't know if there's a free version, but if so it's probably very limited. It's super excellent though. We use mercurial for source control; don't know if they support other source control solutions.
 

TheFatOne

Member
So GAF I'm going to be learning Java this semester at school. I want to buy at least one really good Java book. Does anyone have any recommendations? What can I do to become a better programmer GAF other than practice. I really want to make sure I understand why things are the way they are, and why they work they way they do.
 

ferr

Member
So GAF I'm going to be learning Java this semester at school. I want to buy at least one really good Java book. Does anyone have any recommendations? What can I do to become a better programmer GAF other than practice. I really want to make sure I understand why things are the way they are, and why they work they way they do.

Is it your first programming class? Once you've gotten your feet wet and can handle creating things that you enjoy, independent practice becomes easy, but it takes a couple of classes to get to that comfort level.

If it's your first class, just try not to drown. Otherwise, code as much as you can, make games, make stupid programs that amuse you, etc, to become familiar with a language.
 

ferr

Member
Just went on Reddit and found alot of resources, tips, etc. Definitely recommend checking that site. There's even a reddit for daily programming challenges.

Speaking of programming challenges, doesn't gaf have a monthly challenge? I always seem to see it in the last few days of the competition..
 

TheFatOne

Member
Is it your first programming class? Once you've gotten your feet wet and can handle creating things that you enjoy, independent practice becomes easy, but it takes a couple of classes to get to that comfort level.

If it's your first class, just try not to drown. Otherwise, code as much as you can, make games, make stupid programs that amuse you, etc, to become familiar with a language.

This will be my second programming class. The first class I took was C++, but we didn't go over the object oriented programming parts. Just basic use of C. I really want to make sure I understand how to program, and why things work like they do. I'm just trying to make sure I become the best programmer I can be.
 

Lathentar

Looking for Pants
Hey guys I'm having some trouble writing a stack class template in C++.
I'm going to leave the code here for you to critique but the main points I'm struggling on are removing data when something is popped off the stack and I'm not sure if I am creating new nodes in a correct fashion.

Code:
#include <iostream>

template <class T>
class List {

private:
	struct treeNode{
		T data;
		treeNode *next;
	};

	treeNode start;

public:

	List(T rootData)
	{
		start.data = rootData;
		start->next = null;
	};

	void Push(T data)
	{
		treeNode temp = start;
		start.data = data;
		start->next = makeNode(temp.data);		
	}

	T Pop()
	{
		treeNode temp = start;
		start.data = temp->&left.data;

	}


	treeNode* makeNode(T nodeData)
	{
		treeNode newNode = new treeNode;

		newNode.data = nodeData;
		newNode->next = null;

		return &newNode;
	};
};
You code mixes -> and . operators all over the place (start.data but start->next just in the constructor). I don't see how this would compile.

You need to think a little bit about the overall structure and what needs to happen when you add a new element and remove the top element. Questions to ask yourself... what does an empty stack look like, what does a stack with 1 element look like, what does a stack with N elements look like, what happens when I remove the last element in the stack?
 

Godslay

Banned
So GAF I'm going to be learning Java this semester at school. I want to buy at least one really good Java book. Does anyone have any recommendations? What can I do to become a better programmer GAF other than practice. I really want to make sure I understand why things are the way they are, and why they work they way they do.

I gave this recommendation earlier in the thread. It's still relevant imo.

Headfirst is the most frequently suggested place to start with Java if you haven't programmed before.

http://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208/ref=sr_1_1?ie=UTF8&qid=1344310177&sr=8-1&keywords=headfirst+java

I refresh my Java knowledge from time to time. I recently went through a SCJP book, which was a very good book. 6 is now 7, but I'm not sure if the book has updated yet. This is the book, it assumes you have read through something like HeadFirst Java:

http://www.amazon.com/SCJP-Certified-Programmer-Java-310-065/dp/0071591060/ref=sr_1_1?s=books&ie=UTF8&qid=1338420701&sr=1-1


My personal favorite in order to learn the language a little more in-depth was the complete reference, which is surprisingly readable and technical at the same time. Additionally, it fills in Java 7 features which the previous book didn't cover:

http://www.amazon.com/Java-The-Complete-Reference-Edition/dp/0071606300/ref=sr_1_1?s=books&ie=UTF8&qid=1338420839&sr=1-1

If you want videos, this series from UC Berkeley is very good, and covers a ton of material. You start at the basics and work with common data structures and algorithms in Java:

http://www.youtube.com/playlist?list=PL4BBB74C7D2A1049C
 
So I'm finally going to get serious about working on a side project. I have narrowed it down to either web programming, or an iOS app. I'm looking to build a home setup. Work gives me a laptop, but I want to get something permanent at home. What would be recommended, build a desktop or buy an iMac? I do have a 27 inch monitor that I used to game on, but don't have a stand, guess I could mount it on a wall. Do you guys think a 27 inch iMac and 27 inch secondary monitor would be enough real estate?
 

ferr

Member
So I'm finally going to get serious about working on a side project. I have narrowed it down to either web programming, or an iOS app. I'm looking to build a home setup. Work gives me a laptop, but I want to get something permanent at home. What would be recommended, build a desktop or buy an iMac? I do have a 27 inch monitor that I used to game on, but don't have a stand, guess I could mount it on a wall. Do you guys think a 27 inch iMac and 27 inch secondary monitor would be enough real estate?

Depends on how you want to go about doing iOS programming. I'm looking into Unity 3D which is able to output to multiple platforms like iOS in a Windows based environment. No need for an apple environment until the i'm-taking-this-really-seriously stage.
 
Depends on how you want to go about doing iOS programming. I'm looking into Unity 3D which is able to output to multiple platforms like iOS in a Windows based environment. No need for an apple environment until the i'm-taking-this-really-seriously stage.
Yeah I took an objective-c class while doin my undergrad, so just have a little bit of experience with iOS. I did enjoy it tho. The big issue is coming up with a reasonable sized first project. Im a software engineer by day(PeopleSoft), so I don't have much motivation after programming all day. However, my best friend and coworker who works as one of my designers (people between me and client) wants to work on a side project together. I'm hoping by having a friend to work with will motivate me and keep the process fun and fresh
 
This is more of a question for DBA GAF than Programmer GAF, but perhaps some of you may be able to steer me in the right direction.

Recently we purchased a new server for our development/development database.

Specs:
2x 2.4GHz Intel Xeon E5-2609
32GB RAM
3x 146GB 15K RPM SAS Drives configured in RAID 5
OS: Windows Server 2008R2 Service Pack 1 64-bit

The old server is as following:
1x 2.8 GHz Intel Xeon (5+ year old processor, and I think despite the clock speed it's slower than the new)
4GB RAM
4x HDD 7200 RPM IDE drives in RAID 1, I think ~300GB capacity with the mirroring
OS: Windows Server 2003 32-bit (does this even come in 64-bit?)

Anyway, we have SQL Server 2008 on the old system and SQL Server 2008R2 on the new system.

We have a process that does about 50000 row updates per minute, and has been tested at up to 150,000 row updates per minute. On our old server configuration we have absolutely no problem running the process, neither at the 50k load or the 150k load. On our new machine, which has massively better specs, the process runs so slowly that we get a queue overflow and eventually a failure within about 30 minutes of running the process at best.

I simply can't figure it out. It's properly indexed, we've checked the query execution plans and they're the same on both systems, etc. For some reason the new hardware is simply processing updates at probably around a quarter of the speed of the old server. I've chalked it up to a configuration issue at this point, because it doesn't make sense that it could be a hardware issue. The only hardware issue I could think of is that the new server is configured in RAID 5, which could have a write penalty, but the drives are twice as fast as the old 7200RPM drives, and there's so much more memory that it should be able to minimize the amount of writes it actually needs to make, plus it's got a hardware RAID controller which should help alleviate some of the impact from the RAID 5. I've checked, SQL Server is using around 29GB of the available 32GB, so it's not as if some other process is hogging the memory.

So basically, configuration. Anyone have any tips as to what I may be doing wrong in the configuration to make my new server perform so poorly compared to the 5+ year old machine?

Just and update for anyone who was curious.

I have sort of resolved this issue, though not by finding what configuration setting is different between the servers. I had to set auto commit to false before executing the batch, then commit the batch at the end. If a transaction is committed it will write the data to the disk, and the batch seems to be separating every query in the batch into individual transactions. So basically it's writing to the cache, then writing to the disk every time. By setting autocommit off I save the commit for after the entire batch, which is one long nearly sequential write to disk, so it's much faster than thousands of individual writes. I have always been under the impression that a batch was a single transaction, not a series of them. For some reason on one server I don't need to control the transaction manually and the other I do. I'm not sure why, so I'll post again if I figure that out.

I am actually wondering if it's something wonky with JDBC and not SQL Server at all.
 

dabig2

Member
Hey guys I'm having some trouble writing a stack class template in C++.
I'm going to leave the code here for you to critique but the main points I'm struggling on are removing data when something is popped off the stack and I'm not sure if I am creating new nodes in a correct fashion.

Code:
linked list and stack code

I heavily suggest using a structure pointer in your class template like so:

Code:
private:
	struct treeNode{
		T data;
		struct treeNode *next;
	};
	struct treeNode *top=NULL;

When you rewrite your functions to accommodate this, your code will look cleaner and will make more sense. Here's a possible implementation of a pop function:

Code:
T Pop()
	{
		if (NULL == top){
		return NULL;
		}
		
		struct treeNode *temp = top; //store top in temp
		top = top->next; //pop current top off stack
            	return temp->data; //return node data
	}
 

wolfmat

Confirmed Asshole
Do you guys think a 27 inch iMac and 27 inch secondary monitor would be enough real estate?
Of course! That's a great combo. I have a MacBook, a PC and a Linux server-ish notebook sans screen, and 3 19'' 5:4 monitors, so that's 4 screens, but I only use 2 of them. And that's pretty much enough. I get the most mileage out of Spaces anyway. I also use synergy to only have to use one mouse and one keyboard across all devices, and it works beautifully, so I'll recommend that as well.
What I would strongly suggest if you're going to do iOS work is getting the target devices, if you have the money for it. You don't want to do the bulk of the work in the emulators if you can avoid it.
Best practice: Get the bounding devices in terms of performance constraints (for example, an iPod 3rd gen and an iPad 3rd gen). To develop on them, you'll have to shell out the 100 bucks for the dev license, but that's a yearly payment, so it's easily manageable.
Good luck!
 
So I am almost done school, and I am now in the process of looking ahead toward employment. I'm spending a LOT of my time learning languages and whatnot, trying to get a grasp of some useful skillsets before I start looking. I want to know what advice GAF can give me, in terms of what I should start doing to increase the odds of my employment!

For market health sake, I live in Toronto - so while it's competitive, there are many many opportunities available for me

1. Skills
Right now I'll take next to -any- job I can, just to get into the field, but I also want to have the right foundation of skills to make that possible. As it is, with languages/skills/environments I'm comfy in:

C#, ASP.NET
HTML, CSS, javascript, jQuery
SQLServer, Oracle


What I am currently reading/working on getting good at:

MVC (specifically MVC4 with Razor, razor is a fucking godsend btw)
Linq/Lambda
XML/XSLT
more jQuery (about halfway through Novice to Ninja, amazing book)

What I think I should probably be reading up on more:

JSON/AJAX

2. What the fuck do I do?
Now, with my skillset - am I going in the direction with the stuff I am trying to pick up? Is there anything in particular someone who is looking to apply for entry level jobs should be looking to focus on? Is it normal to feel like I don't know -anything- when looking at the sheer amount of content out there?

What should I be looking to do for a portfolio? Is one even necessary? What sort of questions should I be expecting if I get an interview?

This is all pretty overwhelming to me, as this will be my transition from working crappy retail jobs, to working like... a salary job. The idea is terrifying to me, and I want to really be impressive, advice please!

Don't worry too much. You have a solid skills if you really know the items you listed above. How are your algorithms and data structures skills?

Many entry level jobs for recent CS graduates expect you to know how to program in at least one language, and more importantly the ability to problem solve. At least that's the approach I'm taking when I go recruiting in September for my company. The type of questions I'm planning to ask are geared into seeing how you think and how you break down a problem. Most of the problems I'm gathering to ask candidates don't require domain specific knowledge, only fundamental CS concepts.
 

Slavik81

Member
Code:
T Pop()
	{
		if (NULL == top){
		return NULL;
		}
		
		struct treeNode *temp = top; //store top in temp
		top = top->next; //pop current top off stack
            	return temp->data; //return node data
	}
In C++, this extra 'struct' keyword is unnecessary. Since it's also less clear to add it than to leave it out, I wouldn't bother to include it.
 
Any tips on learning new languages, or is it just practice practice practice? I'm trying to learn Objective C, and I purchased an ebook on it.

Just keep pressing on with examples I guess?
 

Chris R

Member
Any tips on learning new languages, or is it just practice practice practice? I'm trying to learn Objective C, and I purchased an ebook on it.

Just keep pressing on with examples I guess?

If you have a (smallish) project you have completed recently I'd try to convert it over. But then again I'm still trying to get Obj-C down too, just don't use it enough to be comfortable to use it without checking my reference books.
 
Any tips on learning new languages, or is it just practice practice practice? I'm trying to learn Objective C, and I purchased an ebook on it.

Just keep pressing on with examples I guess?
Yeah Ob-c was my most difficult language to learn. Function structures were the first thing to get used to, then learning MVC (my first MVC language)
 

Lathentar

Looking for Pants
In C++, this extra 'struct' keyword is unnecessary. Since it's also less clear to add it than to leave it out, I wouldn't bother to include it.

If you used naming conventions so your structs/class names didn't conflict with local or member variable names it would be even clearer.
 

Zoe

Member
I'm going back and forth on Bugzilla since it's in Perl. But since its been around so long, there's plenty of support.

I might go with Redmine + Git.
 

MJLord

Member
Okay guys I'm still having trouble with my List Template. I have a reading violation and I'm not sure whats causing it. It could be the structure I'm trying to use as the data type or the way I've declared a treeNode. When I go into the variables in debug the pointer "next" has an "CXX0030 Expression Cannot be Evaluated" error along with the "compass" section of the data structure in "data".

Here is my List Template as it stands now.

Code:
#include <iostream>

template <class T>
class List {

private:
	class treeNode{
	public:
		T data;
		treeNode *next;
	};

	treeNode *top;

public:

	List()
	{
		top = 0;
	};

	List(T rootData)
	{
		top.data = rootData;
		top->next = NULL;
	};

	void Push(T data)
	{
		if(top != NULL) //if top is empty
		{
			treeNode temp = *top; //store top into temp
			top->data = data; //new data is placed into top
			top->next = makeNode(temp.data, temp.next); //create new node and point top to it 	
		} else {
			top->data = data;
			top->next = NULL;
		}
	}

	T Pop()
	{		
		treeNode *temp = top; //store top in temp
		top = top->next; //pop current top off stack
        return temp->data; //return node data
	}


	treeNode* makeNode(T nodeData, treeNode* nextPointer)
	{
		treeNode newNode;

		newNode.data = nodeData;
		newNode.next = nextPointer;

		return &newNode;
	};
};

Also here is the "cell" data structure.
Code:
class compass {
public:
	bool north;
	bool south;
	bool east;
	bool west;
};

class cell {
public:
	compass Backtrack;
	compass Solution;
	compass Border;
	compass Walls;
};

Also if you need more information this is all of the code in pastie in case you want more information. It is in a Win32 Project so that I could draw the maze out in GDI when I can get this generating without issues.

http://pastie.org/4452771

Please help me GAF !
 
Do you guys do anything to get you into the right mindset to program? I've been having trouble getting into the right frame of mind lately.
 

Kinitari

Black Canada Mafia
Do you guys do anything to get you into the right mindset to program? I've been having trouble getting into the right frame of mind lately.

Honestly? A tiny bit of some narcotic or another, just enough to calm the constant buzzing in my head that manifests itself into me thinking of 10,000 things to do but never actually getting on task. If you're having trouble because you keep flitting around and are not focusing or sitting still, maybe try having a bit of scotch or something, or whatever it is you like to drink.

Or... you know... non-alcoholic quasi-legal substances (depending on where in the world you live).

Another solution might be to sit down with a pencil and paper (not on the computer) and start writing out what it is you want to do, it helps work me up for the actual programming whenever I do this - usually when I am not feeling particularly motivated.
 

Apoc29

Member
Code:
	treeNode* makeNode(T nodeData, treeNode* nextPointer)
	{
		treeNode newNode;

		newNode.data = nodeData;
		newNode.next = nextPointer;

		return &newNode;
	};

What you're doing here is returning a pointer to a variable which is created on the stack. When this function goes out of scope (immediately upon returning), the pointer becomes invalid.

To make it work, you could do this:

Code:
	treeNode* makeNode(T nodeData, treeNode* nextPointer)
	{
		treeNode* newNode = new treeNode();

		newNode->data = nodeData;
		newNode->next = nextPointer;

		return newNode;
	};

Using the new operator creates the object on the heap, but then you'd need to make sure you call delete on the node when you're done with it to prevent a memory leak.
 

MJLord

Member
To make it work, you could do this:

Code:
	treeNode* makeNode(T nodeData, treeNode* nextPointer)
	{
		treeNode* newNode = new treeNode();

		newNode->data = nodeData;
		newNode->next = nextPointer;

		return newNode;
	};

Using the new operator creates the object on the heap, but then you'd need to make sure you call delete on the node when you're done with it to prevent a memory leak.

Thanks apoc ! That makes sense to me, It's just one of those silly mistakes ain't it.
 

onesvenus

Member
Code:
List(T rootData)
	{
		top.data = rootData;
		top->next = NULL;
	};
This doesn't work as a constructor. You are assigning a variable to a pointer to nowhere. It should be
Code:
List(T rootData)
	{
                top = new treeNode();
		top.data = rootData;
		top->next = NULL;
	};
This way you are reserving space to your new top value.

Code:
void Push(T data)
	{
		if(top != NULL) //if top is empty
		{
			treeNode temp = *top; //store top into temp
			top->data = data; //new data is placed into top
			top->next = makeNode(temp.data, temp.next); //create new node and point top to it 	
		} else {
			top->data = data;
			top->next = NULL;
		}
	}
If top is null, you should create it first reserving space like the previous code snippet I posted or using the makeNode function corrected by Apoc29.

Code:
T Pop()
	{		
		treeNode *temp = top; //store top in temp
		top = top->next; //pop current top off stack
                return temp->data; //return node data
	}
You should delete the old top pointer because you are not freeing the memory occuped by it. Do something like:
Code:
T Pop()
	{		
		T data = top->data; //store top data in an auxiliary var
                treeNode* temp = top; //store top node in temp
		top = top->next; //pop current top off stack
                delete temp; //Free the allocated memory
                return data; //return node data
	}
And finally just a nomenclature advice, what you are building is not a list. When you say list there are some assumptions done, like for example that it supports random insertion and traversal.
With just pop and push methods it's a stack.
In general, take a look at how pointers work and understand them. They are a very useful tool but they can also be a pain when not dealing with them correctly.
 

MJLord

Member
And finally just a nomenclature advice, what you are building is not a list. When you say list there are some assumptions done, like for example that it supports random insertion and traversal.
With just pop and push methods it's a stack.
In general, take a look at how pointers work and understand them. They are a very useful tool but they can also be a pain when not dealing with them correctly.

Thanks, yeah this is an exercise in attempting to use and understand pointers. I understand everything that's been said but I think its just a matter of practising more, I'd love to be able to do this stuff like breathing ! Thanks a lot again !
 
Alright I'm running into an issue in xcode where I run my program, but I get this:

EBzjY.png


and then it gives me a bunch of stuff in assembly language.

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

    @autoreleasepool
    {
        char *choice = NULL;
        double *temperature =NULL;
        Temperature *myTemp;
        myTemp = [Temperature alloc];
        myTemp = [myTemp init];
        
        NSLog(@"Convert to F or C?");
        scanf("%c", choice);
        
        if (*choice == 'f')
        {
            NSLog(@"Enter the temperature");
            scanf("%lf",temperature);
            [myTemp ConvertTempF: *temperature];

        }
        else if (*choice == 'c')
        {
            NSLog(@"Enter the temperature");
            scanf("%lf",temperature);
            [myTemp ConvertTempC: *temperature];
        }
        else
        {
            NSLog(@"Error, invalid choice");
        }
        
    }

    return 0;
}

This is my first real foray into Objective-C so I could be going about this the wrong way. Not included is the interface and implementation portion. I think reading the input from the keyboard is the issue here, but I don't know what to do...
 
Alright I'm running into an issue in xcode where I run my program, but I get this:

EBzjY.png


and then it gives me a bunch of stuff in assembly language.

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

    @autoreleasepool
    {
        char *choice = NULL;
        double *temperature =NULL;
        Temperature *myTemp;
        myTemp = [Temperature alloc];
        myTemp = [myTemp init];
        
        NSLog(@"Convert to F or C?");
        scanf("%c", choice);
        
        if (*choice == 'f')
        {
            NSLog(@"Enter the temperature");
            scanf("%lf",temperature);
            [myTemp ConvertTempF: *temperature];

        }
        else if (*choice == 'c')
        {
            NSLog(@"Enter the temperature");
            scanf("%lf",temperature);
            [myTemp ConvertTempC: *temperature];
        }
        else
        {
            NSLog(@"Error, invalid choice");
        }
        
    }

    return 0;
}

This is my first real foray into Objective-C so I could be going about this the wrong way. Not included is the interface and implementation portion. I think reading the input from the keyboard is the issue here, but I don't know what to do...

I'd say your problem is that you're not allocating/initializing the temperature and choice variables.

Two solutions, keep the current types and allocate the temperature and choice variables, or change the types to char and double respectively then use the address of operator in the function calls that need a character or double pointer.
 

Chris R

Member
Another thing you can do is clean up the three lines

Code:
        Temperature *myTemp;
        myTemp = [Temperature alloc];
        myTemp = [myTemp init];

Into a single line (good to know because you will be doing this a lot...

Code:
        Temperature *myTemp = [[Temperature alloc] init];

and ya, looks like the issue is with your first scanf line (should be &choice right? I know like no C so don't blame me if this is wrong!!!).
 
Another thing you can do is clean up the three lines

Code:
        Temperature *myTemp;
        myTemp = [Temperature alloc];
        myTemp = [myTemp init];

Into a single line (good to know because you will be doing this a lot...

Code:
        Temperature *myTemp = [[Temperature alloc] init];

and ya, looks like the issue is with your first scanf line (should be &choice right? I know like no C so don't blame me if this is wrong!!!).

He declared choice as a character pointer. In this case, his problem is he didn't allocate memory for choice to point to.
 

MooMoo

Member
I'd say your problem is that you're not allocating/initializing the temperature and choice variables.

Two solutions, keep the current types and allocate the temperature and choice variables, or change the types to char and double respectively then use the address of operator in the function calls that need a character or double pointer.
Assuming that Objective C is fairly similar to C (sorry, only know C and Java!), your first proposed solution will still throw an error. In short, an initialization of a pointer variable requires you to use previously initialized variables. If you were to do an initialization like double *temp = 20.0, all this is doing is setting the variable temp to point to whatever is in the memory address location 20; anything could be in this memory location and if you're lucky enough your code will throw an error. This is why the original code is throwing an error; he's setting the pointer variables to point to NULL and when he calls scanf(), he's basically trying to deference null, which you can't do (i.e. a seg fault).

The second solution is sound though and in this case he wouldn't need to bother initializing the variables.

Correct me if my explanation is wrong though :p
 
Derp, knew it was something simple. Didn't need to use the pointer..

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

    @autoreleasepool
    {
        char choice = 0;
        double temperature = 0.0;
        Temperature *myTemp = [[Temperature alloc] init];
        
        NSLog(@"Convert to F or C?");
        scanf("%c", &choice);
        
        if (choice == 'f')
        {
            NSLog(@"Enter the temperature in celsius");
            scanf("%lf", &temperature);
            [myTemp ConvertTempC: temperature];

        }
        else if (choice == 'c')
        {
            NSLog(@"Enter the temperature in fahrenheit");
            scanf("%lf", &temperature);
            [myTemp ConvertTempF: temperature];
        }
        else
        {
            NSLog(@"Error, invalid choice");
        }
        
    }

    return 0;
}

That works. Needed to reference them (right?).
 
Assuming that Objective C is fairly similar to C (sorry, only know C and Java!), your first proposed solution will still throw an error. In short, an initialization of a pointer variable requires you to use previously initialized variables. If you were to do an initialization like double *temp = 20.0, all this is doing is setting the variable temp to point to whatever is in the memory address location 20; anything could be in this memory location and if you're lucky enough your code will throw an error. This is why the original code is throwing an error; he's setting the pointer variables to point to NULL and when he calls scanf(), he's basically trying to deference null, which you can't do (i.e. a seg fault).

The second solution is sound though and in this case he wouldn't need to bother initializing the variables.

Correct me if my explanation is wrong though :p


Um, Im saying to allocate the pointer. In C, it would be malloc. In obj-c it's alloc.
 
Derp, knew it was something simple. Didn't need to use the pointer..

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

    @autoreleasepool
    {
        char choice = 0;
        double temperature = 0.0;
        Temperature *myTemp = [[Temperature alloc] init];
        
        NSLog(@"Convert to F or C?");
        scanf("%c", &choice);
        
        if (choice == 'f')
        {
            NSLog(@"Enter the temperature in celsius");
            scanf("%lf", &temperature);
            [myTemp ConvertTempC: temperature];

        }
        else if (choice == 'c')
        {
            NSLog(@"Enter the temperature in fahrenheit");
            scanf("%lf", &temperature);
            [myTemp ConvertTempF: temperature];
        }
        else
        {
            NSLog(@"Error, invalid choice");
        }
        
    }

    return 0;
}

That works. Needed to reference them (right?).

Yea, that's good.
 
I'm used to c++, so whenever receiving input with scanf I need to reference the variable, like

Code:
scanf("%lf", &variable);

instead of

Code:
scanf("%lf", variable);

right?
 
Top Bottom