• 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.

C++ Help?

Status
Not open for further replies.

luoapp

Member
If you are learning it because you real need it to do scientific calculation/modeling work, I'd suggest you learn GPGPU/CUDA stuff, unless you have some specific requirements. For majority of problems, I think GPU solution is better/cheaper.
 

Toby

Member
MPI is used a lot in scientific/defense fields. In my experience it's also harder to learn/use than the other parallel programming models, so maybe it will look good on the CV?

What broader ideas do you feel like you're missing? I think most companies are happy if you understand mutexes, semaphores, fences, and basic concepts of non-determinism/race conditions.

What I really expected and wanted to learn were the kinds of things you are describing. Things like threading, thread synchronization, mutexes, and semaphores, which were introduced in the OS class but didn't get very detailed. The course description says the class would teach techniques for designing parallel algorithms, like balanced trees, pointer jumping, partitioning, pipelining, etc. but it doesn't look like we'll get into any of that.
I can see how MPI could be used in the application of the things we should be learning, but it just seems like a class focused MPI routines/syntax instead of focusing on parallel algorithms and techniques.
Thanks for the input. I don't really know if my disappointment is justified, but a few of us in the class were thinking about talking to the instructor about it, maybe I'll suggest looking at other parallel programming standards like OpenCL. It's just frustrating because there isn't another course offered that would teach the things I expected to learn, and it feels like I've wasted one of my elective courses.
 

Slavik81

Member
When I took the course tokkun described, it was a 3rd year computer science course called "Operating Systems". Though, there was a bit on various other aspects of operating systems, like permissions. 90% of it was concurrency and how to use synchronization primitives.
 

wolfmat

Confirmed Asshole
Things like threading, thread synchronization, mutexes, and semaphores, which were introduced in the OS class but didn't get very detailed.

I had these topics ad nauseum in diverse classes at uni. Two classes that really dived into them were Embedded Systems and Operating Systems (they thematically flow into each other anyway). The first one dealt mostly with realtime systems, so you should see the relevance. In both cases, there was an accompanying weekly lab course in which we had to apply the material. That obviously taught me the most because it necessitated reading RFCs, framework documentation and stuff.

If you want to get dirty in terms of realtime programming, you could simulate an appropriate embedded system, and program it. I'm not sure what's the standard today, but we did things with a physical Linux-based ARM system called GEME iirc. As a programming environment, we used the QNX Software Development Platform. You should be able to obtain the latter for free as a student, and you should be able to simulate the former with Virtualbox. From that point on, you'd need courseware to guide you through the basic stuff. Maybe talk to a prof about that kind of thing.

If all you want is learn about synchronization, threading and the like, you should get somewhere if you delve into POSIX thread programming.

But let me tell you, it's not trivial at all. There's a lot going on.
 
What I really expected and wanted to learn were the kinds of things you are describing. Things like threading, thread synchronization, mutexes, and semaphores, which were introduced in the OS class but didn't get very detailed. The course description says the class would teach techniques for designing parallel algorithms, like balanced trees, pointer jumping, partitioning, pipelining, etc. but it doesn't look like we'll get into any of that.

I guess it's because school is by definition a theoretical learning approach, and there really isn't much theory to learn behind mutexes and semaphores, an OS class is really the best place and what they teach you there is basically all you need to know about them.

Everything else comes from practice, using them in a real world setting, and learning your operating system of choice's API for accessing them.

Learning about parallel algorithms isn't going to focus on any of the topics you mentioned. Instead, it will be a theoretical approach to designing algorithms that don't even require locking or synchronization in the first place, and discussing the performance characteristics of such algorithms compared to their standard synchronized counterparts.

If you want to learn the practical side of threading and synchronization, get a book like Windows via C/C++ or Win32 Multi-threaded Programming (this book is really old, but it's not like the API has changed very much in the past 10 years).
 
I have a question for c++ programmers out there. Have you ever heard of/used Message Passing Interface (MPI) in your work?
I'm taking a parallel programming course that seems entirely devoted to this instead of the broader ideas of writing parallel algorithms. I'm now really concerned if learning all this is going to be at all useful.

I took a Parallel Algorithms class that used MPI. We didn't really learned it though. Two lectures were devoted to covering the most useful calls, but that was it. The rest of the course was highly theoretical about the techniques you might use to take a sequential algorithm and making it parallel. Lots of Big-O notation modified to cover parallelism and lots of proofs. It was very interesting, but I wish I could have done better in class. There is a really good book on MPI by Pacheco if you need a reference.

edit: Also the class really emphasized parallel architectures using "hypercubes."
 

Bruiserk

Member
A couple of questions to cement my understanding of struct vs class:

1) What is a non-obvious benefit to using either one of these in a program? I understand that it helps with organizing your program by not having a set of different variables laying around but that is about it.

2) Are there any other differences between struct and class other than having to explicitly state whether something is private or public respectively? Why would one choose a class over a struct? Or is it just a preference thing?
 

McHuj

Member
I have a question for c++ programmers out there. Have you ever heard of/used Message Passing Interface (MPI) in your work?
I'm taking a parallel programming course that seems entirely devoted to this instead of the broader ideas of writing parallel algorithms. I'm now really concerned if learning all this is going to be at all useful.

Yes. I write mainly in C/Assembly (not actually C++) with an API derived from MPI almost every day (for the past several years). I agree with others that it is painful, but it can be very powerful. At my job, we're looking at it for low power many core processors that have only small distributed memories (no large shared memory and no cache hierarchy).

It does place a large burden on the programmer because not only do you have to split your task's computation into a parallel implementation, you have to explicitly manage the memory as well.

I haven't programmed the CellBE, but imagine programming the SPU's is very similar (you explicitly have to DMA the memory you want to an SPE). The benefit for us is that caches, shared memories, and their management hardware can be power hungry and thus can be omitted from the chip (at the expense of the programmer).

I can't speak to your class specifically, but it's good to be exposed to as many methods of parallelization as possible.
 

tokkun

Member
A couple of questions to cement my understanding of struct vs class:

1) What is a non-obvious benefit to using either one of these in a program? I understand that it helps with organizing your program by not having a set of different variables laying around but that is about it.

It's tough to give a succinct answer to that. I would say the general point to object-oriented programming, besides the conceptual/organizational aspect, is to make it easier to re-use code. When you learn about concepts like inheritance, polymorphism, and interface vs implementation, that will be easier to understand.

2) Are there any other differences between struct and class other than having to explicitly state whether something is private or public respectively? Why would one choose a class over a struct? Or is it just a preference thing?

In pure C++, that is the only difference. The reason that both types exist is related to backwards compatibility with code written in C.
 

GaimeGuy

Volunteer Deputy Campaign Director, Obama for America '16
An entertaining thought exercise I've seen trip up more than a few people both in classrooms and in the professional world:

You have an std vector, myvector, which was declared as follows:

std::vector myvector<Object *>;

There is one entry in the vector (in other words, size = 1).

You want to properly delete the entry from the vector.

What, if anything, is wrong with the following method of doing so? And how can it be fixed if it is an issue?

delete &myvector[0];
 

Wichu

Member
An entertaining thought exercise I've seen trip up more than a few people both in classrooms and in the professional world:

You have an std vector, myvector, which was declared as follows:

std::vector myvector<Object *>;

There is one entry in the vector (in other words, size = 1).

You want to properly delete the entry from the vector.

What, if anything, is wrong with the following method of doing so? And how can it be fixed if it is an issue?

delete &myvector[0];

Off the top of my head, it frees the memory belonging to the object, but the pointer stays in the vector. You'd have to call myvector.erase(0); too (still calling delete so the memory gets freed).
 
Off the top of my head, it frees the memory belonging to the object, but the pointer stays in the vector. You'd have to call myvector.erase(0); too (still calling delete so the memory gets freed).

delete vector[0];

Is correct. The OP's version is calling delete on an Object**

The erase issue is still true though, but just use vector.clear()

A common cleanup pattern is

Code:
for (auto it=v.begin(); it!=v.end(); ++it)
     delete *it;
v.clear();
 

Wichu

Member
delete vector[0];

Is correct. The OP's version is calling delete on an Object**

The erase issue is still true though, but just use vector.clear()

A common cleanup pattern is

Code:
for (auto it=v.begin(); it!=v.end(); ++it)
     delete *it;
v.clear();

Oops, missed that one. Wouldn't the compiler detect that, though?
 
Oops, missed that one. Wouldn't the compiler detect that, though?

Delete operates on any pointer type. Object** is a pointer type, just that the pointed-to type happens to be an Object*.

Object** ppObj = new Object*;

Is perfectly valid and indeed there are situations where you want to do this. In that situation, calling delete on the Object** is the only way to free up the memory correctly.

In fact, the internal implementation of vector almost certainly does this when reallocating, and in fact the original code does exactly that - frees the memory for vector's underlying array of pointers.
 

GaimeGuy

Volunteer Deputy Campaign Director, Obama for America '16
:)

It's very misleading to look at because the abstraction is almost like emptying out a box within a box.

Yes, delete myvector[0]; is what to do if you want to free up the memory for the object. Then you remove the pointer from the vector with myvector.erase(0) (or myvector.clear()).






delete &myvector[0] has the effect of freeing up the memory used to store the Object *.
At that point, there is a risk of a memory leak: The object still resides in memory allocated for it. but the area of memory which tells us where the object is located can be written to by anything.
 
delete &myvector[0] has the effect of freeing up the memory used to store the Object *.
At that point, there is a risk of a memory leak: The object still resides in memory allocated for it. but the area of memory which tells us where the object is located can be written to by anything.

Memory leak is the least of your concerns. The second the vector goes out of scope your program will crash / segfault, because vector's destructor will call delete on it again :)
 

KorrZ

Member
Okay, I need help :( I'm chugging along trying to teach myself C++, and I'm getting into Classes and constructors. So this book has me working with a Fraction class and a string constructor so you can create arrays of fraction objects by using strings "1/2" "3/4" etc.
I keep getting "warning: depreciated conversion from string constant to 'char*'" the program runs but crashes immediately prints out "Using string constructor" but that's it. If I just use one number : "5" it works for the default case and makes it "5/1" but it fails as soon as I try to enter the whole fraction.

Here's the entire code, I bolded the parts that specifically relate to what I'm trying to get working:

Code:
#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

class Fraction {
private:
    int num,denom;

public:
    //Constructors
  [B]  Fraction (char *s);  //string constructor[/B]
    Fraction (Fraction const &src) {set(src.num,src.denom);} //copy constructor
    Fraction () {num = 0; denom =1; } //default constructor
    Fraction (int n, int d) {set (n,d);}
    //Member functions
    void set(int n, int d)  {num = n, denom = d, normalize();}
    int get_num() {return num;}
    int get_denom() {return denom;}
    Fraction add (Fraction other);
    Fraction multi (Fraction other);

private:
    int gcf (int a,int b);
    void normalize ();
    int lcm (int a, int b) {int n = gcf (a, b) ; return a / n * b;}
};
[B]
int main (){

Fraction arr_frac[3] = {"1/2", "3/4", "4/6"};
for (int i=0; i < 4; i++)
cout << arr_frac[i].get_num() << "/" << arr_frac[i].get_denom() << endl;

return 0;
}[/B]


void Fraction::normalize(){
if (denom == 0 || num == 0){
    num = 0;
    denom = 1;
}

if (denom < 0) {
    num = num * -1;
    denom = denom * -1;
}

int n = gcf(num, denom);
num = num / n;
denom = denom / n;

}

int Fraction::gcf (int a, int b){
if (b == 0)
    return abs(a);
else
   return gcf (b, a%b);
}

Fraction Fraction::add (Fraction other) {
Fraction fract;
int lcd = lcm (denom, other.denom);
int quot1 = (lcd / denom);
int quot2 = (lcd / other.denom);
fract.set(num * quot1 + other.num * quot2, lcd);
return fract;

}

Fraction Fraction::multi(Fraction other){
Fraction fract;
fract.set(num * other.num, denom * other.denom);
return fract;
}

[B]Fraction::Fraction(char *s) {
int n = 0;
int d = 1;

cout << "Using string constructor ";
char *p1 = strtok(s, "/, ");
char *p2 = strtok(NULL, "/, ");
if (p1 !=NULL)
    n = atoi(p1);
    if (p2 !=NULL)
    d = atoi(p2);
set(n,d);
}[/B]
 

Slavik81

Member
String literals are placed in read-only memory and cannot be modified.
strtok modifies the string that is passed into it.
You are passing string literals into strtok.

String literals normally are const char*, thus the warning you receive when you use them as char*. You need to make a temporary copy of the string if you want to be able to pass literals into the Fraction constructor like that. I think strdup will make you one (though you'll need to remember to delete it when you're done with it. Double-check its documentation).

It seems kind of odd to me, though, that a C++ book is using so much of the C library.
 

RiZ III

Member
Okay, I need help :( I'm chugging along trying to teach myself C++, and I'm getting into Classes and constructors. So this book has me working with a Fraction class and a string constructor so you can create arrays of fraction objects by using strings "1/2" "3/4" etc.
I keep getting "warning: depreciated conversion from string constant to 'char*'" the program runs but crashes immediately prints out "Using string constructor" but that's it. If I just use one number : "5" it works for the default case and makes it "5/1" but it fails as soon as I try to enter the whole fraction.

Use strtok_s instead of strtok to get rid of the warning.

As for the crash, it is happening because strtok expects a string buffer. You aren't passing in a buffer, you are passing in a string literal. You need to pass in a char buffer like: char buffer[] = "1/2".

Also, you are overstepping the array here:
Fraction arr_frac[3] = {"1/2", "3/4", "4/6"};
for (int i=0; i < 4; i++)

You should only be going up to 3.
 
I haven't programmed the CellBE, but imagine programming the SPU's is very similar (you explicitly have to DMA the memory you want to an SPE). The benefit for us is that caches, shared memories, and their management hardware can be power hungry and thus can be omitted from the chip (at the expense of the programmer).

Yes, no MMU, either, and all memory load/stores are wrapped to the LSLR mask, so if you reference >256k (eg, local store) it just wraps around to the beginning of memory. It's good times, as you can imagine.

I'm surprised to hear MPI is used in low power multicore envs, for some reason in my head it was always a high-overhead API for supercomputer systems. Neat!
 

KorrZ

Member
Thanks to both of you. Yeah this book is really odd, it feeds me wrong programs that need fixing all the time. It's called "C++ Without Fear Second Edition" it's meant to be for complete beginners to programming.

You can see, it gives you the function for that string constructor with none of the warnings about string literals that you guys gave me, I'm thinking I might need to ditch and get a new book :\.

urD1U.png

xJgUt.png
 
Thanks to both of you. Yeah this book is really odd, it feeds me wrong programs that need fixing all the time. It's called "C++ Without Fear Second Edition" it's meant to be for complete beginners to programming.

You can see, it gives you the function for that string constructor with none of the warnings about string literals that you guys gave me, I'm thinking I might need to ditch and get a new book :\.

-snip-

Yeah, that's a very bad bad example. strtok modifies the buffer (specifically it places a null in the buffer). In most modern compilers, string literals are readonly segments of memory. So, when you try to write into that segment of memory, it's going to segfault under linux or crash under windows (also segfaulting but it won't be reported unless your compiler is in debug mode)

A note: You don't really need to break the fraction string into tokens.

Something like this would be better and cheaper if you must rely on c constructs for implementation.

Code:
int n = 0;
int d = 1;
char *dstr = NULL;

if(s != NULL)
{
    dstr = strstr(s, "/");
    n = atoi(s);
}

if(dstr != NULL)
{
    d = atoi(dstr + 1);
}

if(d == 0)
{
//handle exception
}

atoi always converts a number up til a non-digit character is encountered. Thus, to atoi, the '/' naturally splits the character array anyway.
 

Slavik81

Member
Thanks to both of you. Yeah this book is really odd, it feeds me wrong programs that need fixing all the time. It's called "C++ Without Fear Second Edition" it's meant to be for complete beginners to programming.

You can see, it gives you the function for that string constructor with none of the warnings about string literals that you guys gave me, I'm thinking I might need to ditch and get a new book :\.

I agree. Here's some recommendations: tinyurl.com/so-cxxbooks

Though, are you a complete beginner to programming? If you already have experience in other languages, that might affect the recommendations.
 

KorrZ

Member
I agree. Here's some recommendations: tinyurl.com/so-cxxbooks

Though, are you a complete beginner to programming? If you already have experience in other languages, that might affect the recommendations.

I've been using this book for a few months, but aside from that yes. The 2-3 months I've spent with C++ so far is the extent of my programming knowledge. I'm thinking about ordering C++ Primer Plus 6th edition, would you recommend it?


A note: You don't really need to break the fraction string into tokens.

Something like this would be better and cheaper if you must rely on c constructs for implementation.

Code:
int n = 0;
int d = 1;
char *dstr = NULL;

if(s != NULL)
{
    dstr = strstr(s, "/");
    n = atoi(s);
}

if(dstr != NULL)
{
    d = atoi(dstr + 1);
}

if(d == 0)
{
//handle exception
}

atoi always converts a number up til a non-digit character is encountered. Thus, to atoi, the '/' naturally splits the character array anyway.

Thanks, I really didn't know how else to do it except breaking it into tokens like in the book, or that I was using a lot of "C" things rather than C++. My only basis for the language so far is this book and I'm starting to think it's taught me some wrong things.
 

TheBez

Member
So I am taking a basic C++ class as my first programming foray so forgive me if this is a little too simple :)

I need to write a program that asks the user to input two integers. Store the integers in two separate variables and using the conditional operator determine which integer is the smaller of the two. With what I have so far I can input two variable but for some reason it seems to only be using the first digit of the two numbers inputted. Why is that?

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s1, s2;
	cout << "Please input two numbers" << endl;
	cin >> s1;
	cin >> s2;

	cout << endl;
	
	if(s1 > s2)
		cout << s1 << " is the larger number" << endl;
	else if(s2 > s1)
	    cout << s2 << " is the larger number" << endl;
	
return 0;
}
 

Haly

One day I realized that sadness is just another word for not enough coffee.
With what I have so far I can input two variable but for some reason it seems to only be using the first digit of the two numbers inputted. Why is that?
Giving us an example of output would help here.

Just looking at it, your problem seems to be related to not turning the strings s1 and s2 into integers. Right now you're comparing two strings, which has its own rules for comparison that are different from comparing integers.

Look into the atoi function.
 

KorrZ

Member
So I am taking a basic C++ class as my first programming foray so forgive me if this is a little too simple :)

I need to write a program that asks the user to input two integers. Store the integers in two separate variables and using the conditional operator determine which integer is the smaller of the two. With what I have so far I can input two variable but for some reason it seems to only be using the first digit of the two numbers inputted. Why is that?

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s1, s2;
	cout << "Please input two numbers" << endl;
	cin >> s1;
	cin >> s2;

	cout << endl;
	
	if(s1 > s2)
		cout << s1 << " is the larger number" << endl;
	else if(s2 > s1)
	    cout << s2 << " is the larger number" << endl;
	
return 0;
}

Change
Code:
string s1,s2;
into
Code:
int s1, s2;

string is a text string where as integers are dealing with the actual numbers.
 

Slavik81

Member
I've been using this book for a few months, but aside from that yes. The 2-3 months I've spent with C++ so far is the extent of my programming knowledge. I'm thinking about ordering C++ Primer Plus 6th edition, would you recommend it?
Alas, I moved into C++ having come through other languages. I don't really have any personal suggestions for someone learning C++ as their first language.
 

TheBez

Member
Change
Code:
string s1,s2;
into
Code:
int s1, s2;

string is a text string where as integers are dealing with the actual numbers.

Hmm, thank you. I was trying to get it to accept two inputs earlier but I clearly must've been doing something very wrong :p
 

KorrZ

Member
Hmm, thank you. I was trying to get it to accept two inputs earlier but I clearly must've been doing something very wrong :p

Not a problem, just think of it like this:
int is the raw numbers 2+2 = 4
string is just the text "2" "2"+"2" = "22" or "Hello" + "World" = "HelloWorld"
 
Thanks to both of you. Yeah this book is really odd, it feeds me wrong programs that need fixing all the time. It's called "C++ Without Fear Second Edition" it's meant to be for complete beginners to programming.

You can see, it gives you the function for that string constructor with none of the warnings about string literals that you guys gave me, I'm thinking I might need to ditch and get a new book :\.


Honestly, do yourself a favor and get a new book. Everything about the 2 pages you screenshoted is obsolete and outdated. Seriously, do not learn C++ the way this book is teaching it or you will just learn the wrong way of doing everything.
 
Code:
#include<stdio.h>

//Declarations
void input(double *);
double Ang_Vel (double, double, double);
double tip_speed (double, double, double);
void output(double, int, double);

int main ()

{
//Variables
double d = 0.0; //diameter of propeller in meters
int s = 0.0; //shaft speed of propeller
double w = 0.0; //angular velocity
double t = 0.0; //tip speed
double PI = 0.0; //PI


//Get input
input(&d);

//Calculate acceleration for various RPMs
for (s = 1000; s < 10400; s = s + 1000)
	{
		w = Ang_Vel(s,PI,w);
		t = tip_speed(w,d,t);
		output(d,s,t);
	}

return 0;

}

//Input Function

void input(double *d)
{
  int done = 0;

  while (done == 0)
  {
    printf("Enter propeller diameter in meters:\n");
    scanf("%lf",d);
    if (*d > 0.0)
    {
      done = 1;
    }
    else
    {
      printf("Invalid propeller diameter\n");
    }
  }

}


//Calculation Functions

//Angular velocity
double Ang_Vel(double s, double PI, double w)
{
	PI = 3.14159265;
	w = (2 * PI * s); //angular velocity
	return w;
}

// Tip Speed
double tip_speed(double w, double d, double t)
{
	t = (w * d)/ 60;
	return t;
}

//Output Function
void output (double d, int s, double t)
{
	printf("A propeller with a Diameter of %f meters and a Shaft Speed of %d rpm, has a tip speed of %f meters/second\n", d, s, t);

}


and my output

Code:
Enter propeller diameter in meters:
2.10
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 1000 rpm, has a tip speed of 219.911485 meters/second
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 2000 rpm, has a tip speed of 439.822971 meters/second
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 3000 rpm, has a tip speed of 659.734457 meters/second
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 4000 rpm, has a tip speed of 879.645942 meters/second
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 5000 rpm, has a tip speed of 1099.557428 meters/second
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 6000 rpm, has a tip speed of 1319.468913 meters/second
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 7000 rpm, has a tip speed of 1539.380399 meters/second
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 8000 rpm, has a tip speed of 1759.291884 meters/second
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 9000 rpm, has a tip speed of 1979.203370 meters/second
A propeller with a Diameter of 2.100000 meters and a Shaft Speed of 10000 rpm, has a tip speed of 2199.114855 meters/second


How to I limit the output to 2 places after the decimal?
 

tokkun

Member
You are using more arguments than you need in those functions. You can declare local variables inside the function rather than passing them all as arguments.

For example, in the angular velocity function, there is no need to pass PI or w.
 
I went back and cleaned up the functions as was recommended and went over my lecture notes and the part in the chapter the talked about them and I've got a better grasp of it now

Sorry to blow this thread up with questions, but I have one more:


Code:
#include<stdio.h>

int main ()
{

int i = 0;


	printf("How much of the Fibonacci Sequence would you like to display? (Enter an Integer 0 or greater):\n");

	scanf("%d", &i);
	
	fibonacci(&i);

return 0;
}

// Fibonacci Sequence Function
int fibonacci(int i)
{
  int a = 0;
  int b = 1;
  int sum;
  int n;

  for (n=0; n <= i; n++)
  {
    printf("%d\n",a);
    sum = a + b;
    a = b;
    b = sum;
  }

  return 0;
}


My problem is that the loop doesn't stop once it reaches the value of 'i'. It just continues and I have to close my compiler. I've got the for loop formatted right, and I don't understand why the loop doesn't end.
 

wolfmat

Confirmed Asshole
My problem is that the loop doesn't stop once it reaches the value of 'i'. It just continues and I have to close my compiler. I've got the for loop formatted right, and I don't understand why the loop doesn't end.

You're passing the ADDRESS of i as an argument. That's probably something like 0x123786234 (a memory address). You should pass the value. Ditch the & before the i when you call fibonacci.
 
I had thought that since I didn't declare the functions with pointers (*) prior to the main function (like I did in the code in Post #1235) that I would have to use pointers in the main function?? Something to that effect was mentioned in lecture, but I must have been confused about the context.

anyway, program runs. thanks again
 

maharg

idspispopd
And the only reason it compiles at all is because you're letting the compiler create an implicit declaration of fibonacci that can take any number of any type of arguments. It wouldn't even compile if you were using C99 or a C++ compiler. And for good reason, it's a big flaw in C89 and only there because of a much more primitive attitude towards function definitions.
 

wolfmat

Confirmed Asshole
I had thought that since I didn't declare the functions with pointers (*) prior to the main function (like I did in the code in Post #1235) that I would have to use pointers in the main function?? Something to that effect was mentioned in lecture, but I must have been confused about the context.
I'm not sure what you're talking about. You either use pointers or you don't. There's no "you have to". You can always just operate on data.

Pointers are what the name suggests. To get from a pointer to the underlying data, provided there is data and not another pointer, you need to use the dereferencing operator.

In your example, it would look like this:
Code:
#include<stdio.h>

int main ()
{

int i = 0;
[B]int *pointer;[/B]

	printf("How much of the Fibonacci Sequence would you like to display? (Enter an Integer 0 or greater):\n");

	scanf("%d", &i);
	[B]pointer = &i;[/B]
	fibonacci([B]pointer[/B]);

return 0;
}

// Fibonacci Sequence Function
int fibonacci([B]int *pointer[/B])
{
  int a = 0;
  int b = 1;
  int sum;
  int n;

  for (n=0; n <= [B]*pointer[/B]; n++)
  {
    printf("%d\n",a);
    sum = a + b;
    a = b;
    b = sum;
  }

  return 0;
}

Edit: Wingin it here, hope I didn't mess something up.
 
I used to know C++ in university, but haven't used it in a while. I want to do some recreational programming and refresh myself with the language. Is there a free compiler and assembler I can download to get started now? What's the best?
 

Dmented

Banned
I used to know C++ in university, but haven't used it in a while. I want to do some recreational programming and refresh myself with the language. Is there a free compiler and assembler I can download to get started now? What's the best?

I don't know the best but there's Microsoft's Visual C++ Express that is free.
 

wolfmat

Confirmed Asshole
I used to know C++ in university, but haven't used it in a while. I want to do some recreational programming and refresh myself with the language. Is there a free compiler and assembler I can download to get started now? What's the best?

If you want to get going IMMEDIATELY and are running Windows, you could get http://www.bloodshed.net/devcpp.html
It ships with MinGW, which is the environment used to compile with the help of GNU tools and gcc.

It works.
 
I used to know C++ in university, but haven't used it in a while. I want to do some recreational programming and refresh myself with the language. Is there a free compiler and assembler I can download to get started now? What's the best?

Depends on your platform and comfort level. Visual Studio Express on Windows as mentioned, XCode on OSX, gcc+whatever editor on OSX , gcc+whatever editor on Cygwin, gcc+whatever editor on mingw32, etc.

I personally run emacs+gcc+gdb+make on a variety of platforms.
 

Slavik81

Member
I have to say, I've fallen in love with Qt Creator. They've really turned it into a nice IDE. The only things that still keep me stuck on Visual Studio are VAX and some custom plug-ins.

I used to know C++ in university, but haven't used it in a while. I want to do some recreational programming and refresh myself with the language. Is there a free compiler and assembler I can download to get started now? What's the best?

You probably want to snag an IDE as well.

On Windows, Visual Studio Express is solid. Cross-platform, there's Code::Blocks, Eclipse, and (if you're working with Qt) Qt Creator.

If you're on Windows and you don't go with Visual Studio, you'll probably need MinGW. It may or may not be installed along with those IDEs.
 
Status
Not open for further replies.
Top Bottom