• 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

I'm not sure I understand what this all means.

So the function would take an int like 23, convert it to the string "23", convert that string "23" into the string "17" (23 is 17 in hexadecimal), and then convert that "17" into the int 17?

And this was bad/wrong because numbers are stored in binary so there was no real need to do all those conversions?

The underlying storage format in memory is a bit of a red herring. "0x17" and "23" and
"0b10111" and "027" and "XXIII" are all string representations of the same number. There's no reason to ever convert a decimal number to hex. You just take the number that you've got and display it as a hex number.

The function the students wrote took in (int) 23, converted it to (string) "23", converted that to string "17", then converted it back to (int) 23. The function literally didn't do anything.
 

JeTmAn81

Member
I'd say it would be better to write true == understand instead of understand == true.

That's exactly the same test, it won't change anything here.

But in most languages that uses == to perform a test of equality, "true" (or any immediate value) isn't a correct lvalue. By getting used to the idea of placing the immediate value to the left of ==, you'll get compiler errors each time you write = instead of == by mistake, instead of a silent bug (or, if you're really lucky, a compiler warning).

It may be slightly less natural, especially at first, but it's really a nice trick.

Sounds like a good idea.

Code:
if (understand != true) {
    return false;
}

if (understand != false) {
    return true;
}
I've seen it.

For real.


Granted, you can see anything in students code...

One of my best memories is this one: a group of 5 had to design (with a lot of help) a compiler for a given language. They call me for help, because they have a bug they can't find after a whole day looking for it.

They explain me that they have an int that contains a decimal integer. The want to convert it in an hexadecimal integer.

It took me a whole minute to understand what they wanted to do (read: a function that takes x and returns x, or in other terms something totally useless because they didn't understand at all the principles of binary storage of values).

They designed a function that would:
- allocate a buffer
- convert the int into a string in the buffer where the number is in its decimal form
- work on the string to convert it to hexadecimal form, just with character manipulation
- convert the string into an int

5 people and a whole day to write a function that do nothing... with a bug inside.

Their faces when I managed to explain them why they were completely wrong were priceless. I know you do a lot of bad things when you learn, I've done plently of them myself. but still, for students in their third year in one of the best computer science school of the country, that was quite unexpected for the fresh teacher I was.

Just to make sure I'm understanding this issue correctly, if you have a decimal representation of an integer and want the hex representation, you need to do this:

1. If the decimal is represented as a string, convert it to an integer value (this could be a variable in higher level languages or simply memory storage in lower levels). This will be represented as binary in memory.

2. Take your binary integer representation and run it through a string operation that knows how to convert the binary data to a hex string.
 
Sounds like a good idea.



Just to make sure I'm understanding this issue correctly, if you have a decimal representation of an integer and want the hex representation, you need to do this:

1. If the decimal is represented as a string, convert it to an integer value (this could be a variable in higher level languages or simply memory storage in lower levels). This will be represented as binary in memory.

2. Take your binary integer representation and run it through a string operation that knows how to convert the binary data to a hex string.

The issue was they didn't want a string representation of anything. They wanted an in-memory representation of it. And they thought they had to do some kind of conversion to get that, presumably so that they could do arithmetic operations on hex numbers, instead of arithmetic operations on decimal numbers. It doesn't matter if you want your number in base 37, it's still going to be binary in memory. The only time you convert anything is when you're printing it.
 

Koren

Member
I'm not sure I understand what this all means.

So the function would take an int like 23, convert it to the string "23", convert that string "23" into the string "17" (23 is 17 in hexadecimal), and then convert that "17" into the int 17?

And this was bad/wrong because numbers are stored in binary so there was no real need to do all those conversions?
The int "23" and the int "0x17" are exactly the same thing, id est

00000000 00000000 00000000 00010111

Int in memory aren't tied to a base (or if they do, it's binary)

If the function is bug-free, it does nothing but use a huge number of cycles to do nothing.
 

JeTmAn81

Member
The issue was they didn't want a string representation of anything. They wanted an in-memory representation of it. And they thought they had to do some kind of conversion to get that, presumably so that they could do arithmetic operations on hex numbers, instead of arithmetic operations on decimal numbers. It doesn't matter if you want your number in base 37, it's still going to be binary in memory. The only time you convert anything is when you're printing it.

Yeah, they were definitely confused. I can see how that could happen with hex vs. decimal, though, since hex doesn't really have a purpose in computing other than convenient shorthand, right? This doesn't seem to be addressed very well in CS education.
 

Koren

Member
Sounds like a good idea.



Just to make sure I'm understanding this issue correctly, if you have a decimal representation of an integer and want the hex representation, you need to do this:

1. If the decimal is represented as a string, convert it to an integer value (this could be a variable in higher level languages or simply memory storage in lower levels). This will be represented as binary in memory.

2. Take your binary integer representation and run it through a string operation that knows how to convert the binary data to a hex string.
Mostly, yes...

In C:

Code:
char* value = "23"

/* convert decimal string to int */
int val; 
sscanf(value, "%d", &val);

/* write int as hex string */
printf("%x", val);

They had to do exactly this... The scanf was done in a lex/yacc routine, they mostly had to convert the tree produced by their compiler into a text file containing assembly. But the assembly needed the immediate values in hex form (you just had to use %x in printf).

They added a
Code:
ConvertToHex(&value)
Before the printf that was doing nothing because they hadn't understood what is stored in a int (which is a binary value that isn't tied to a decimal or hexadecimal representation)
 

Koren

Member
Yeah, they were definitely confused. I can see how that could happen with hex vs. decimal, though, since hex doesn't really have a purpose in computing other than convenient shorthand, right? This doesn't seem to be addressed very well in CS education.
That can be an issue, obviously. And with the new standards for decimal floats, it'll become even more important to understand how it works.

It's not awfully difficult to grasp, though, if explained propoerly, I've been teached the difference between binary storage and bcd storage in school when I was 12 (and I learned it myself at 9).

Hexadecimal is indeed of no use in pravtical computing, it's just a better way to represent binary values than binary. Especially useful for bit masks, for example.
 
That can be an issue, obviously. And with the new standards for decimal floats, it'll become even more important to understand how it works.

It's not awfully difficult to grasp, though, if explained propoerly, I've been teached the difference between binary storage and bcd storage in school when I was 12 (and I learned it myself at 9).

Hexadecimal is indeed of no use in pravtical computing, it's just a better way to represent binary values than binary. Especially useful for bit masks, for example.

Well, that's what practical means right? Its practical use is that it has a trivial mapping to binary, yet is drastically more friendly to humans
 

JeTmAn81

Member
Well, that's what practical means right? Its practical use is that it has a trivial mapping to binary, yet is drastically more friendly to humans

Maybe it would be more accurate to say it has no effect on lower level code representations and hardware. It's definitely practical when it comes to saving time much like high level language constructs are.
 

Koren

Member
Yes, I probably picked the wrong word. I meant the hexadecimal was purely for humans, not for actual electronic circuitry.
 
Yes, I probably picked the wrong word. I meant the hexadecimal was purely for humans, not for actual electronic circuitry.

Well, the idea of representing the presence or absence of an electric charge by writing down a 0 or a 1 is purely for humans too. I think of hexadecimal and binary notation as functionally equivalent: just two different ways of notating raw binary data, with hex being superior because it's compact.
 

JeTmAn81

Member
Well, the idea of representing the presence or absence of an electric charge by writing down a 0 or a 1 is purely for humans too. I think of hexadecimal and binary notation as functionally equivalent: just two different ways of notating raw binary data, with hex being superior because it's compact.

Binary has the advantage of being a direct isomorphism to the physical elements of the system. If you've got 10011001 in memory, there's a block of memory registers somewhere that goes on/off/off/on/on/off/off/on.
 

Koren

Member
I agree with JeTmAn81. Hex is compact, but it also hide all the operations on bits. When you encounter c3 xor 85, I doubt that 81 is a natural answer.

Take microcontrollers where you can define the direction of each bit of ports, it totally void the meaning of hex values.

At least, bits are most of the time a direct mapping of physical properties.

Using hex for IEEE floats is also cumbersome, you mix sign with exponent and exponent with mantiss.

It's really handy for compactness, but half of the time, you need the binary representation to understand the coding anyway...
 

Moosichu

Member
I've been really busy at Uni lately so haven't posted here as much as I have wanted to. Although over the next few weeks we are meant to be implementing a ray-tracer in Java, and I have decided to use C++ because I want to learn more C++ and I'm bored of Java, so expect me to start posting here a lot!

A bit of a plug: My Uni has also been really lacking in that it doesn't really have a hackathon. Literally the moment I thought that an email came through from the Computer Lab saying that another student was starting one. So purely by good timing, I have managed to become a founding member of our University's hackathon! We hit a big milestone today as applications have just opened. http://www.hackcambridge.com/. It is open to anyone currently at University, if anyone is interested.

I was a tutor for a while and remember a student who had made it through a couple programming classes and didn't know how to compile a program.

It was more depressing than anything. I feel bad that so many people were wasting their time at school.

When I worked at an IT company. I helped manage a subversion repo we hosted for a client. Said client had recently lost their only programmer and had hired a new one. This new kept on calling asking really strange and unusual questions which I answered. After a few conversations I straight up asked him if he had ever used a version control system before and he asked "What's a version control?", to which I replied, "Similar to Subversion", to which the response was "What's a Subversion?".
 
I have a career and résumé related question... What kind of projects would be great to work on for the purpose of résumé building?

I have a friend who wants to build up her portfolio within a month. She's looking to make a project or something in Java that would really make her résumé look good to prospective employers.

I suggested making small, simple things such as a very simple HTTP server using Java's Sockets, which is an approximately 40 liner thing that I think would really show an understanding of a thing or two about deeper knowledge than what you'd probably learn at school.

But she thinks maybe making one larger, "complete" project that has all the eye candy and bells and whistles would probably be more attractive.

So, yeah, any ideas? And thanks!
 

w3bba

Member
I have a career and résumé related question... What kind of projects would be great to work on for the purpose of résumé building?

I have a friend who wants to build up her portfolio within a month. She's looking to make a project or something in Java that would really make her résumé look good to prospective employers.

I suggested making small, simple things such as a very simple HTTP server using Java's Sockets, which is an approximately 40 liner thing that I think would really show an understanding of a thing or two about deeper knowledge than what you'd probably learn at school.

But she thinks maybe making one larger, "complete" project that has all the eye candy and bells and whistles would probably be more attractive.

So, yeah, any ideas? And thanks!

generally I would say working with Web APIs, like REST is a good and very relevant thing at the moment. very general and needed by most. in terms of scope also very scalable.
 
I suggested making small, simple things such as a very simple HTTP server using Java's Sockets, which is an approximately 40 liner thing that I think would really show an understanding of a thing or two about deeper knowledge than what you'd probably learn at school.

But she thinks maybe making one larger, "complete" project that has all the eye candy and bells and whistles would probably be more attractive.

She has the right of things. The issue with trivial projects is that it is hard to actually learn lessons from them, not just about how to code but about how to produce and "ship" software. It's also difficult to get passionate enough about trivial items, but actually not too hard to get excited to make something interesting that you care about.

If she's looking to make a stronger resume, interview better, and generate opportunities, then a real project running in the cloud and available on github for review will open those doors.

My suggestion to her is start w/ Spring Boot or Java Spark (I much prefer the latter) and build out a API (REST) that interacts with data for a subject that she finds interesting. You can slap a simple bootstrap web front end on top of it running in another app and call into her API. Run it all to the cloud.
 

Koren

Member
I straight up asked him if he had ever used a version control system before and he asked "What's a version control?", to which I replied, "Similar to Subversion", to which the response was "What's a Subversion?".
I'm not even slightly surprised...

I worked with a senior engineer in our national communication company. He wasn't able to use a mutex or a semaphore correctly, when his job was to do parallel computing... You can imagine how bad the things were going with shared memory.
 
Thanks for the responses!

She has the right of things. The issue with trivial projects is that it is hard to actually learn lessons from them, not just about how to code but about how to produce and "ship" software. It's also difficult to get passionate enough about trivial items, but actually not too hard to get excited to make something interesting that you care about.

If she's looking to make a stronger resume, interview better, and generate opportunities, then a real project running in the cloud and available on github for review will open those doors.

My suggestion to her is start w/ Spring Boot or Java Spark (I much prefer the latter) and build out a API (REST) that interacts with data for a subject that she finds interesting. You can slap a simple bootstrap web front end on top of it running in another app and call into her API. Run it all to the cloud.

Well I guess personally I do tend to feel more passionate about the smaller projects because they're faster to make and I don't need to worry about that last 90% of the code (the polish, UI, etc.) so I loved coding things like a web server and a CHIP-8 virtual machine, each of which did teach me a lot.

But that said, I understand what you mean about having a larger project "shipped" and working. Personally I'm not terribly knowledgeable about building RESTful web sites (I only know of vert.x and Dropwizard, which I used last summer for an internship), so thanks for the suggestions of frameworks to use.
 
So I'm thinking up an idea with a friend that requires a cross-platform desktop application and an online web service. Since I've got experience with C# and .NET that whole stack is starting to look appealing since we can just live in .NET and deploy everything between platforms now. Two problems though:
  • I don't really know how mature the .NET framework is on Linux and Mac yet. Specifically, I don't know what we would even do for UI since WPF isn't working on those platforms to my knowledge
  • Something like Python or Java might be a better fit, but it's outside the scope of the technologies I'm pushing to learn before I get out of school

Advice?
 

Moosichu

Member
So I'm thinking up an idea with a friend that requires a cross-platform desktop application and an online web service. Since I've got experience with C# and .NET that whole stack is starting to look appealing since we can just live in .NET and deploy everything between platforms now. Two problems though:
  • I don't really know how mature the .NET framework is on Linux and Mac yet. Specifically, I don't know what we would even do for UI since WPF isn't working on those platforms to my knowledge
  • Something like Python or Java might be a better fit, but it's outside the scope of the technologies I'm pushing to learn before I get out of school

Advice?


Have you looked into Xamarin? It supports Windows, OSX and mobile platforms.

AFAIK it's the 'way' to do C# cross-platform.
 

YoungFa

Member
What is a good (preferably free) online service to host crawlers? I need to crawl reddit and twitter and other boards for a university project (predicting oscars) and we cant let them run on our home computers/laptop all the time. Does anyone of you know a good place to host that?
 

Makai

Member
So I'm thinking up an idea with a friend that requires a cross-platform desktop application and an online web service. Since I've got experience with C# and .NET that whole stack is starting to look appealing since we can just live in .NET and deploy everything between platforms now. Two problems though:
  • I don't really know how mature the .NET framework is on Linux and Mac yet. Specifically, I don't know what we would even do for UI since WPF isn't working on those platforms to my knowledge
  • Something like Python or Java might be a better fit, but it's outside the scope of the technologies I'm pushing to learn before I get out of school

Advice?
Unity. I've used it for nongame applications.

Actually nah, if you want a traditional WPF interface.
 
Kinda need help on these one I need to find the sum of all the even numbers between 1 through 10. I might not be getting the formula right I tried a couple.


#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;

int main()

{
int i, firstNum;
double secondNum , n1, n2;
char letter = 65 ;

n2 = 0;
n1 = 0;
cout << " Enter first number: " << endl;
cin >> firstNum;
i = firstNum;
i = i + 1;


cout << " Enter second number: " << endl;
cin >> secondNum;

secondNum = secondNum - 1;

while (i >= firstNum && i <= secondNum)
{
if (i % 2 == 1)
cout << i << endl;

i++;

if (i % 2 == 0)
{
n1 = i +n1;
n2 = (i + static_cast<int>(sqrt(i))) - 1;
i++;
}

}

/*part e*/
cout << " The the sum of the square of the all odd numbers is " << n2 << endl;
cout << " The sum of the all even numbers is " << n1 << endl;
cout << " The square number is " << static_cast<int>(sqrt(i)) << endl;
/* part f*/
while (letter >= 65 && letter < 90)
{

cout << letter << " " ;
letter++;
}


I don't want someone to do my work for me I'm just stuck.
 
What is a good (preferably free) online service to host crawlers? I need to crawl reddit and twitter and other boards for a university project (predicting oscars) and we cant let them run on our home computers/laptop all the time. Does anyone of you know a good place to host that?

Can't you use a computer at school?

Most cheap hosting providers have policies against long-running processes. I don't have any experience but I think you could do this with AWS.

Kinda need help on these one I need to find the sum of all the even numbers between 1 through 10. I might not be getting the formula right I tried a couple.

I think you have a major misunderstanding but I can't identify what it is exactly. You've got the modulo part correct but I have no idea why you brought square roots into it.

You want to use a variable to store the result. You're going to loop from firstNum to secondNum and add the loop counter to the result variable if it is even (% 2 == 0). After the loop completes, the result variable will contain the sum. Does that make sense?

someone's probably going to chime in that you can make it more efficient by having the loop step by two, but I don't want to overcomplicate things by introducing too many concepts at once
 

mercviper

Member
Kinda need help on these one I need to find the sum of all the even numbers between 1 through 10. I might not be getting the formula right I tried a couple.





I don't want someone to do my work for me I'm just stuck.

Okay well looking at the code you're doing a bunch of weird things.

1) you decrease the value of the second number, which might throw it off if the second number given in your range is even

2) you have both the even formula and the odd formula running when the number is even, as opposed to split

3) you're getting square roots of the odd number? From the text later in the code it sounds like you want summed squares, not roots.

4) you increment i twice in the loop. This is probably the biggest culprit. Perhaps it's because you forgot to enclose the odd part in brackets, but really you want to increment interators at the end of the loop unless you're doing something tricky.
 
What is the error you're seeing?

I'm not getting a error . I need to find the sum of the even numbers between the first number and the second number ( in this case 1 and 10 so the sum should be 30, I think) . I'm getting 28 .


Okay well looking at the code you're doing a bunch of weird things.

1) you decrease the value of the second number, which might throw it off if the second number given in your range is even

2) you have both the even formula and the odd formula running when the number is even, as opposed to split

3) you're getting square roots of the odd number? From the text later in the code it sounds like you want summed squares, not roots.

4) you increment i twice in the loop. This is probably the biggest culprit. Perhaps it's because you forgot to enclose the odd part in brackets, but really you want to increment interators at the end of the loop unless you're doing something tricky.


Those has something to do with other parts of the one code I have to do. I decreased the value of the secondNum because I need to output the odd numbers between the two user inputs, so if it is something like 7 and 9( it will decrease to 8 so it would not show up because it is looking for odd numbers at that point if that makes sense), it shouldn't be outputted or it just should not show when I output. The square is another part I had to do.
 

mercviper

Member
Okay. 5) you increment the first number before you even do anything with it

i=firstNum;

followed immediately by

i=i+1;

This causes you to start your loop at 2, and before you get to the even portion of your loop you've increased the number to 3, skipping the 2 at the beginning of the loop. a range of 0-10 will get you 30.

Since it looks like you will have to deal with odd numbers too, messing with the ranges will probably give you problems with that portion of your work. Also it's kinda unnecessary to mess with ranges to make them work. You are able to handle the odd/even with the modulus if statements you have alone.
 
I'm not getting a error . I need to find the sum of the even numbers between the first number and the second number ( in this case 1 and 10 so the sum should be 30, I think) . I'm getting 28 .

This is an important clue. You should know exactly what sum you're expecting and asking yourself what the code could be doing to get the wrong result.
Code:
2+4+6+8+10 = 30
4+6+8+10 = 28
A likely hypothesis is the code is skipping the 2. Now you know to look carefully at how the start point of the loop is being set.

This kind of thought process is a big part of what programming is all about. Always know what you're expecting and what's different. Error messages are really valuable and should always be carefully read. It's like you're a detective looking for clues to solve a mystery.
 

Rush_Khan

Member
I'm not getting a error . I need to find the sum of the even numbers between the first number and the second number ( in this case 1 and 10 so the sum should be 30, I think) . I'm getting 28 .


I'm not sure why you're subtracting 1 from secondNum. Assuming firstNum = 1 and secondNum = 10 (without the line, 'secondNum=secondNum-1'), you could do the following to calculate the sum of even numbers (I get 30 when I run it):

Code:
for (i=firstNum; i <=secondNum; i++) {
        if (i % 2 == 0) {
            n1+=i;
        }
        else {
            //i is odd. Do something else here.
        }
}

Edit: n % 2 can only be either 0 or 1 for integers, so instead of having separate if statements, maybe combine them into an if else.

Edit 2: Looking at your code, it seems when i%2==0, you increment i by one. i is now odd so it will run the code within the next if statement (i%2==1 because i is now odd). Could be the problem.
 

poweld

Member
I'm not getting a error . I need to find the sum of the even numbers between the first number and the second number ( in this case 1 and 10 so the sum should be 30, I think) . I'm getting 28 .

Sure sounds like an error to me! If you're having trouble and want help, you've got to provide us with what your problem is, not just that you have one.

I'm a bit busy atm, but it seem like others can help out. If not I'll check in later.
 

mercviper

Member
Those has something to do with other parts of the one code I have to do. I decreased the value of the secondNum because I need to output the odd numbers between the two user inputs, so if it is something like 7 and 9( it will decrease to 8 so it would not show up because it is looking for odd numbers at that point if that makes sense), it shouldn't be outputted or it just should not show when I output. The square is another part I had to do.

Yeah but you already have that accounted for with the if statements in your loop.

The idea I'm getting is your hw asks you to iterate through the range and when i == odd, you output the number, then square it (not root) and keep an ongoing total for the sum of odd squares.

when i==even, you just keep an ongoing total for the sum of even numbers.

The key to this is the if statements. You won't need to modify the ranges ahead of time to fix that.
 
iFVJqrc.jpg


can anyone tell me what int cap means for the answer to question a?

i would have written (int x, int y) for the answer

like in question e) i wrote int sum(int x, int y) and not sum(int x, int cap)
 
can anyone tell me what int cap means for the answer to question a?

i would have written (int x, int y) for the answer

like in question e) i wrote int sum(int x, int y) and not sum(int x, int cap)

The cap is not significant. It's just whatever you choose to name the second parameter. int max(int x[], int y) would be a valid answer.

The first parameter needs to be declared as an array or pointer though, so int max(int x, int y) is incorrect.
 
The cap is not significant. It's just whatever you choose to name the second parameter. int max(int x[], int y) would be a valid answer.

The first parameter needs to be declared as an array or pointer though, so int max(int x, int y) is incorrect.

aahhh i mean int x[] for that part lol, but thanks a bunch for responding

what a relief :p
 

mercviper

Member
aahhh i mean int x[] for that part lol, but thanks a bunch for responding

what a relief :p
While cap isn't significant, it's still helpful To use meaningful variables so when you look at it later you know that the second variable represents the size of your array. Basically it's for readability and will save headaches for anything you want to maintain long term.
 
Time to play help this person solve their segmentation fault problems!

Code:
#include <stdio.h>
#include <cs50.h> 
#include <string.h>

int main(int argc, string argv[]) {
    string output = "";
    //Set key to command line value
    int key = atoi(argv[1]);
    //Prompt user for text to be encrypted
    printf("Enter text to be encrypted: ");
    string input = GetString();
    
    for(int i = 0, n = strlen(input); i < n; i++) {
        output[i] = (input[i] + key) % 26;    
    } 
    printf("The output is %s\n", output);
}

I don't know why I'm so bad at this. :l Like always, feel free to burn my code faults into my skin if I broke any best practices or did something inefficiently.

gdb is telling me that the error is coming from this line

Code:
    int key = atoi(argv[1]);

and that my argv is pointing to a null value. But I have no idea how to fix that.
 
While cap isn't significant, it's still helpful To use meaningful variables so when you look at it later you know that the second variable represents the size of your array. Basically it's for readability and will save headaches for anything you want to maintain long term.

i think ill go by this just to be safe while still acknowledging the insignificance of cap

thank you :)
 
While cap isn't significant, it's still helpful To use meaningful variables so when you look at it later you know that the second variable represents the size of your array. Basically it's for readability and will save headaches for anything you want to maintain long term.

Yeah, I was going to make this point but it's pretty muddy because I think "cap" is still a pretty crappy name for a variable representing the size of an array. I'd go with "size". Or something like int max(int a[], int asize);
 
Time to play help this person solve their segmentation fault problems!

Code:
int main(int argc, string argv[])

gdb is telling me that the error is coming from this line

Code:
    int key = atoi(argv[1]);

It's been almost 10 years since I've done any C++ but I'm pretty sure you can't prototype main with string as the second argument. It should be

Code:
int main(int argc, char** argv)
or
int main(int argc, char* argv[])
 
It's been almost 10 years since I've done any C++ but I'm pretty sure you can't prototype main with string as the second argument. It should be

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

I'm actually doing just C! But I will have to look into using char* instead of string. I've always been using string and not had any issue as of yet, but I just started learning a few days ago so I'm probably missing something.

I found the issue as well though! I wasn't thinking about memory allocation, but when I initialized output as " ", I am assuming the computer only gave it enough memory to hold that single character. My guess is that I was trying to shove more memory into it than it was allocated, so to fix that I just initialized it as the input string so it would always have the same amount of characters. Well... that's what I thought I was doing. Either way, it works now. Except for the fact that my Caesar shift logic needs to be adjusted to only give me letters of the alphabet...
 
What is a good (preferably free) online service to host crawlers? I need to crawl reddit and twitter and other boards for a university project (predicting oscars) and we cant let them run on our home computers/laptop all the time. Does anyone of you know a good place to host that?

If you haven't started coding it, you could do something like this with Node.js and Agenda ( I assume you want something that runs every X minutes) pretty easily and push to Azure App Service or a Cloud Foundry platform as a service implementation. You're very unlikely to use enough bandwidth or compute to get past most services' free trial/"free to play" tier.
 
I'm actually doing just C! But I will have to look into using char* instead of string. I've always been using string and not had any issue as of yet, but I just started learning a few days ago so I'm probably missing something.

I found the issue as well though! I wasn't thinking about memory allocation, but when I initialized output as " ", I am assuming the computer only gave it enough memory to hold that single character. My guess is that I was trying to shove more memory into it than it was allocated, so to fix that I just initialized it as the input string so it would always have the same amount of characters. Well... that's what I thought I was doing. Either way, it works now. Except for the fact that my Caesar shift logic needs to be adjusted to only give me letters of the alphabet...

There isn't a string data type in C, though. C just uses pointers to char. I'm thinking cs50.h has something like this in it, which will find and replace "string" with "char *". I'm guessing you're taking a class and the instructor doesn't want to have to cover pointers yet, so s/he's trying to limit your exposure.
Code:
#define string char *

String literals in C are read only. That means that this code is invalid:
Code:
char* x = "Hello, world";
x[0] = 'J'; /* Undefined behavior, writing to string literal */

You might get away with writing data into them but that triggers the dreaded undefined behavior, which means it could be fine on one computer but crash on another.

Anyway, if you can search cs50.h for anything that's being done with "string" it'd be a lot easier to troubleshoot.

Edit: Ha, weird coincidence but the first example in the Wikipedia article for Undefined behavior is the same as mine.
 
There isn't a string data type in C, though. C just uses pointers to char. I'm thinking cs50.h has something like this in it, which will find and replace "string" with "char *". I'm guessing you're taking a class and the instructor doesn't want to have to cover pointers yet, so s/he's trying to limit your exposure.
Code:
#define string char *

Code:
typedef char *string;

is the first thing defined in the library. So you're spot on. I should probably make a habit of using the pointer version from here on out.
 
Code:
typedef char *string;

is the first thing defined in the library. So you're spot on. I should probably make a habit of using the pointer version from here on out.

Yep, so to avoid the undefined behavior you need to define output as an array of char instead of a char pointer. Then you should be good.
 

Moosichu

Member
I'm about to go to bed so won't be able to reply to any responses until I wake up, but this has been frustrating me for a bit and I don't know what I have done wrond and my C++ debugging skills are still quite poor.

I'm going to comment this code more properly tomorrow as well.

Essentially, we have to make a basic ray-tracer that runs on the CPU as an assignment. We've been told to do it in Java, but I asked if I could do it in C++ instead as I want to learn C++ and got told yes, so I decided to whack the following code together tonight (using Handmade Hero's framebuffer which Casey very kindly let my use). All the relevant stuff is in https://github.com/Moosichu/RayTracer/blob/master/src/ray_tracer.cpp.

However, when I run my program, nothing is being drawn to the screen :(, and I can't work out why.

The reason I think the error is here, is because if I set the ambientFactor color to a value, the entire screen will be filled with that. It's just that no circles are being drawn which is what I want essentially as I have just implement the ambient component of spheres.
Code:
Color traceRay(Ray ray,
               Sphere sceneObjects[], std::size_t numObjects,
               PointLight lights[], std::size_t numLights,
               int recurseDepth) {
    LightCollision closestCollision;
    closestCollision.position = {600000.0, 60000.0, 60000.0}; //TODO(Tom) Replace with max possible scalar values
    closestCollision.normal = {1.0, 0, 0};
    closestCollision.ambientFactor = {0, 0, 0};
    closestCollision.diffuseFactor = {0, 0, 0};
    closestCollision.specularFactor = {0, 0, 0};

    //Find the closest position
    for(std::size_t i = 0; i < numObjects; i++) {
        //TODO(Tom) Have a way of handling type of sceneObject
        {
            Sphere sphere = sceneObjects[i];

            Vector3D sphereToRayOrigin = sphere.position - ray.origin;
            scalar a = ray.direction.dot(ray.direction); //a = |ray.direction|^2
            scalar b = 2 * ray.direction.dot(sphereToRayOrigin);
            scalar c = sphereToRayOrigin.dot(sphereToRayOrigin) - (sphere.radius*sphere.radius);
            scalar d;
            {
                double intermediate = (b*b) - (4*a*c);
                if(intermediate < 0) {
                    continue; //No intersection
                }
                d = sqrt(intermediate);
            }

            double s1 = (-b + d)/(2*a);
            double s2 = (-b - d)/(2*a);
            double s = s1 < s2 ? s1 : s2; //select the closest point intersection
            if(s < 0) {
                continue;
            }
            
            //Work out the position of the collision relateve to the camera's location
            Vector3D collisionOffset = ray.direction * s;
            if(collisionOffset.square() < closestCollision.position.square()) { //Comparing magnitudes
                closestCollision.position = collisionOffset;
                //TODO(Tom) Calculate the normal of the collision!
                closestCollision.ambientFactor = sphere.ambientFactor;
                closestCollision.diffuseFactor = sphere.diffuseFactor;
                closestCollision.specularFactor = sphere.specularFactor;
            }
        }
    }

    
    Color finalColor = closestCollision.ambientFactor;
    if(recurseDepth > 0) {
        Color diffuseComponent;
        Color specularComponent;

        //check to make sure any diffuse components actually have to be calculated
        if (closestCollision.diffuseFactor.red |
            closestCollision.diffuseFactor.green |
            closestCollision.diffuseFactor.blue) {
            //TODO(Tom) recursively calculate diffuse components and add to final color variable
            
        }

        //check to make sure any specular components actually have to be calculated
        if (closestCollision.specularFactor.red |
            closestCollision.specularFactor.green |
            closestCollision.specularFactor.blue) {
            //TODO(Tom) recursively calculate specular component and add to final color variable
        } 
    }
        
    return finalColor;
}

Sorry about this huge code dump, I'm very tired and something glaringly obvious will probably jump out in the morning, but I also have a huge fear that I will spend hours trying to track down a niggly bug.
I'm guessing the error is somewhere in my collision detection section, but I did already implement this in java and it worked fine and I have just been porting my work there to C++ so there shouldn't be any issues with the basic maths.
 
Top Bottom