Archive for the ‘C / C++’ Category

Function vs Method

Tuesday, March 8th, 2011

The main difference between a function and a method is that a function can live independently of the any instance of a class, where as a method sits within a class.

That is about it, e.g. a function is

int func(int value);
...
 
int main()
{
  cout << funct(3) << endl;
}

whereas a method has to live within a class

class myclass
{
    int myMethod(int it);
};
 
....
 
int main()
{
   myclass theclass;
   cout << theclass.myMethod(4) << endl;
}

Strings

Tuesday, March 8th, 2011

Just a small thing encase anyone else finds this interesting as such.. but you cannot add a set of ” ” strings together in c++ without declaring one being a string.. for example

cout << "hi" + "bye" << endl;

the error would be

error: invalid operands of types 

Why -> and not *name.type

Tuesday, March 8th, 2011

When you are coding with pointers in c++ and you want to access the function/variable from that pointer deferenced, how come you cannot use something like below.

struct typeT{
   int value1;
};
 
typeT* tt = new typeT;
*tt.value1;

it is because the access element of the variable tt is higher in the compiler and thus it tries to equate

tt.value1

first, which is not a good thing because the tt has not been de-referenced and thus it is just a memory address pointer to the actual object. so you need to do

(*tt).value1

because like in maths the () will be equated first and then the access element part “.” and thus to make it easier

tt->value1

will change to

(*tt).value1

within the compiler.

CS107 – Assignment 2 – Six degrees

Wednesday, August 25th, 2010

This is assignment 2 from a older CS107 course, because the latest course work is held on a UNIX server which in turn you need access to!!.. kinder does not help when you do not have access too!!.. Here is where I got the files from cs107 link, there is a zip file at the bottom of that page which has all of the assignments and handouts etc.

I have included the PDF of the assignment in the above file link, but since the actual assignment includes a few massive files you can download them from the CS107 link of the whole course work that I am using from the cs107 link.

As a note, within my linux setup, I need to setup the environment variable to tell the program to use a Linux little endian by

export OSTYPE=linux

Basically the assignment is to load in cast/movie details (which the base code from the assignment already does for use) and then we are needed to pull out the data from the structure of the file, the structure of the actors is (as taken from the PDF file)

  1. The name of the actor is laid out character by character, as a normal null-terminated C-string. If the length of the actor

struct – setup and memory locations

Friday, July 23rd, 2010

When you setup a struct within c++, it is kinder like having a array of data and if you want to you can access the internal parts by using some memory pointer location fun!.

Lets say that you have a struct of

struct intvalue {
    int a;
    int b;
};

Just to say that since I am using int(eger) values so that is what I am incrementing by in the pointer arithmetic which is why I am casting the pointer to a integer value.

So lets say that we create a variable of intvalue and setup the values as below

intvalue testvalue;
testvalue.a = 4;
testvalue.b = 5;

We can then pull out the value of a or b, but using memcpy and just outputting to a int(eger) variable as below, the key is the ((int*)&testvalue)+1, this will first convert the testvalue variable to a pointer to memory location and then (int*) casts that pointer to a int pointer, because internally that is what it is, and then just add 1 to it, which points to the second value ( in this case the value of b which is 5)

    int avalue;
    // convert to a int pointer type and then add one to it (to the next array element as such).
    memcpy(&avalue, ((int*)&testvalue)+1,sizeof(int));
    cout << "a value (or is it the b value :) ) " << avalue << endl;

The output would be

a value (or is it the b value :) ) 5

because I am pointing to the second value which is b and thus 5 :) .

Of course if you just wanted the value of first int (the value of a in this case) you do not add the 1 to the memory location, for example

    memcpy(&avalue, ((int*)&testvalue),sizeof(int));

this time I am just converting the testvalue (casting) to a int pointer and thus pointing to the start of the struct and that is where the int a variable is living :) .

CS107 – Assignment 1 – Context Free Grammar – Random Sentence Generator

Wednesday, July 14th, 2010

This is assignment 1 from a older CS107 course, because the latest course work is held on a UNIX server which in turn you need access to!!.. kinder does not help when you do not have access too!!.. Here is where I got the files from cs107 link, there is a zip file at the bottom of that page which has all of the assignments and handouts etc.

The basics of a context free grammar is (as taken from the PDF file attached which is the assignment 1 in more details), the tokens as such are the <..> parts of the block, so that you start at <start> and then you print out “The ” and then goto the <object> block to then print out a randomly picked object to then print out the <verb> if there is any blocks within the object/verb then do them before heading back to the last word on the <start> block which is “tonight”. That is it, it generates random text :) .

The Poem grammar
{
<start>
	The <object> <verb> tonight. ;
}
 
{
<object>
	waves	;
	big yellow flowers ;
	slugs ;
}
 
{
<verb>
	sigh <adverb> ;
	portend like <object> ;
	die <adverb> ;
}
 
{
<adverb>
	warily ;
	grumpily ;
}

So the assignment is mainly to get used to compiling up programs within a Linux/Unix environment, I was using qt-creator IDE (which has placed some files within the zip file attached, but it does not effect the directory structure as such). To compile on Linux/Unix as long as there is a Makefile you can just

make

So, the assignment 1 base code reads in the textual files and all is required is to output the text within a random sentence and repeat 3 times, so the start of the code does the looping and calls the doRandomText function which requires as parameters the mapped (map) grammar and where to start ()

  for (int i =1;i <= 3; i++)
  {
      cout << "Version #" << i << endl << endl;
      doRandomText(grammar, "<start>");
      cout << endl << endl;
  }
  return 0;
}
 
// recursive loop in the text and produce randomly generated text
void doRandomText(map<string, Definition> theGrammar, string terminal)
{
    Definition def = theGrammar[terminal];
    assert(def.getNonterminal().size() !=0);
    Production prod = def.getRandomProduction();
    for (Production::iterator prodIter = prod.begin(); prodIter != prod.end(); prodIter++)
    {
        string theText = *prodIter;
        if (theText.at(0)=='<' && theText.at(theText.size()-1)== '>')
            doRandomText(theGrammar, theText);
        else
        {
            if (theText == "," || theText == ".")
                cout << theText;
            else
                cout << " " << theText;
        }
    }
}

The recursive function above basically tries to find the terminal within the grammar definitions and if there is not one, exit the code (assert), else print out the textual data whilst iterating over them, if there is any more terminals within the sentence then goto that terminal by calling this same function.

Here is the output of a run from the program.

./rsg assn-1-rsg-data/excuse.g 
The grammar file called "assn-1-rsg-data/excuse.g" contains 7 definitions.
Version #1
 
 I need an extension because my disk got erased, and I'm sure you've heard this before, but I had to make up a lot of documentation for the Navy in a big hurry, and I'm sure you've heard this before, but my printout was enshrowded in a mysterious fog for three days and then vanished, and I'm sure you've heard this before, but all my pencils broke, and just then I had 7 programs in like, a billion different langauges, and if you can believe it, I just didn't feel like working, and and then if I recall correctly I had to worry about the Winter Olympics, and and then if I recall correctly my disk got erased, and as if that wasn't enough I forgot how to write.
 
Version #2
 
 I need an extension because I got stuck in a blizzard at Tahoe, and then get this, my Mac was enshrowded in a mysterious fog for three days and then vanished.
 
Version #3
 
 I need an extension because I didn't know I was in this class, and then I just didn't feel like working, and I'm sure you've heard this before, but I thought I already graduated, and then, just when my mojo was getting back on its feet, the bookstore was out of erasers, and if you can believe it, I didn't know I was in this class, and and then if I recall correctly my dorm burned down.

Explicit – c++ what is it for ?

Wednesday, July 14th, 2010

The explicit keyword in c++ is make sure that user of your class only creates and uses the class only creates it in the way that you was expecting and not via any references as such.

For example in the following code example

class mainClassWith {
public:
    // this basically will setup the internal_value equal to the value that is passed from the user
    explicit mainClassWith(int value) : internal_value(value) {} ;
 
    int internal_value;
};
 
int functionWith(const mainClassWith &theClass)
{
    cout << "the value with " << theClass.internal_value << endl;
}

The functionWith will take a parameter of mainClassWith of which has a explicit keyword on its constructor, this means that if we try and do something like

    mainClassWith mainWith(4);
 
    functionWith(mainWith);

then the compiler will compile and also the output would be printed to the screen of “the value with 4″, but since we know that the mainClassWith takes a integer value as a constructor and try to bypass any object creation of that mainClassWith and try and do this

functionWith(3);

then the compiler will complain because we cannot setup a mainClassWith on the fly like this and let the compiler pass a value of “3″ to the class and hope that it works!!!, we have explicitly declared that the constructor must be initialised before using.

But if we did take off the explicit keyword as in the class example below.

class mainClassWithOut {
public:
    // this basically will setup the internal_value equal to the value that is passed from the user
    mainClassWithOut(int value) : internal_value(value) {} ;
 
    int internal_value;
};
 
int functionWithout(const mainClassWithOut &theClass)
{
    cout << "the value without  "<< theClass.internal_value << endl;
}

then we are able to call the new function (functionWithout) without actually setting up the object and allow the compiler to make up its own instance of that object and pass to the function.

functionWithout(5);

would work and the output would be “the value without 5″ which is correct, but the compiler and created the mainClassWithout object and setup with the value of 5 via its constructor, which if there was a few different constructors etc then how would you be sure that the correct constructor was called and thus would the value that you want back from the class really be 5, it could be 0 and another value be that 5!!.