thelamb 163 Posting Pro in Training

Yes, so how should you go about 'debugging' this?
First, look at the line where you got this error:

cout << p1[i];

Here, you say 'print the ith element of the array p1'. Now lets look at how p1 is declared:

double p1 = *p++;

It's a double!, not an array of doubles.

You should simply discard 'p1' and use 'p' everywhere:

cout << p[i];
thelamb 163 Posting Pro in Training

Your question is impossible to answer. How am I suppose to give a value to how difficult it will be for you?
All I know, from my own experience, is that for me it is easiest to learn a language by just starting to write a project in it. This doesn't need to be a useful program, the important thing is to start writing code, and to start shooting yourself in the foot so that you learn what not to do.

Also, print out a copy of the standard (or keep a PDF if you don't want to print ~700 pages double sided) and try to look for things in there when you're stuck, it will teach you 'how' to read the standard, and give valuable insight.

Also the game development question is difficult to answer. I imagine being _very_ comfortable with C++ is a prerequisite, it will probably also help if you've made a game yourself, or helped in developing an open source game (and you can prove that you did).
But this is all just guessing, don't expect to become good enough in C++ within a year though.

thelamb 163 Posting Pro in Training

If you only read the elements of a then everything is fine, yes.
Also, please don't be so lazy to write 'd' for 'the' - it is very annoying to read sentences like that.

thelamb 163 Posting Pro in Training

There is a big OS development community here:
http://forum.osdev.org/index.php with a wiki: http://wiki.osdev.org/Main_Page

Usually, hobby-OS projects are compiled with a GCC cross compiler. There is a document on the OSDev WIKI about how to set this up. In early stages, the kernel can not depend on anything from from libc - so a stripped down compiler is necessary.

While it is possible to write an OS is assembly, it is hardly ever done any more.
I'm not really sure what your question about inline-asm in C with regard to Windows/Linux is, but:
If you will ever write a Windows kernel driver, you _can_ use inline asm but it is _highly_ discouraged. Mainly because the ASM is platform dependent, and very very easily breaks on someone else's machine.
That is why only minor parts of an OS are written in ASM.

The book for 32bit asm will do fine, as you will probably write a 32 bit OS (don't start with a 64 bit kernel).

You don't need to burn the OS to a CD every time you test it, there are virual machines like Qemu, Bochs etc.
You will 'just' compile your kernel, stick in the boot loader, and tell one of these virtual machines to load it as if it were a floppy disk.

thelamb 163 Posting Pro in Training

_TCHAR is typedef'd as 'char' when your project uses 'ANSI' settings, it is typedef'd as 'WCHAR' when your project is unicode.

wprintf is just like printf, but instead it takes a const WCHAR* as input, not a const char*.

L before a string literal ("string") tells the compiler that this is a UNICODE string. Without the L you would get an error 'no acceptable conversion from const char* to const WCHAR*', as then the compiler would treat " ----------\n" as an ANSI string.

Btw, you should never deal with void main, main should always return an int.

thelamb 163 Posting Pro in Training

http://www.cplusplus.com/reference/string/string/

Scroll down to 'String operations:'.

You can use functions like find, compare etc.

thelamb 163 Posting Pro in Training

No, your error handling is not exactly correct. I've seen many of our students do the same as you did though.

What exactly is pthread_exit meant for? To exit _from_ a posix thread. But in your case the thread that calls pthread_create is not a posix thread. So you can just exit();

Also, there is a special output file descriptor for error messages, called stderr. It is better to print errors to this, instead of to stdout like you are doing now. You can use fprintf for that.

Now on to your array problem. You need to understand that an array in C is basically a pointer. When you write int A[x]; where x is initialized as atio(argv[1]); you are using a feature from C99, you should make sure that your teacher agrees with this.

I think your teachers intention is that you use malloc to allocate a 2D array, and pass that to the functions. I will show you how to do it with a 1D array then it's up to you to extend this to 2D.

// in main:
int* A = (int*)malloc( x * sizeof(int) ); 

pthread_create(&tid,&attr,matrixA, (void*) A);

// in matrixA
... matrixA( void* param ) {
    int* A = (int*)param;
    // use A here 
}

If you want to pass a struct to the thread:

typedef struct threadArgs {
    int* matrixA;
    int* matrixB;
} threadArgs_t;

int main() {
 // creating matrix A and B

 threadArgs_t threadArgs;
 threadArgs.matrixA = A; …
cbreeze commented: helped me a lot +0
ddanbe commented: Great help. +15
thelamb 163 Posting Pro in Training

You can create an std::map, that maps the strings to integral values. Then call map::find and use the returned iterator to retrieve the key and use that in the switch switch statement.

thelamb 163 Posting Pro in Training

It depends on the instruction, there are shortcuts for longer commands, which in assembly are 2 or 3 'words' but in binary are just 1 opcode.

As an example:
xor eax,eax
Is smaller than
mov eax, 0

Also, take a relative jump for example - it's 5 bytes, but a far jump is 7 (32-bit).

thelamb 163 Posting Pro in Training

Then my answer still stands, m_item will be initialized based on its type ;).

If DataType is an int, m_item will be initialized as if it were written 'int m_item;'.

So if you call insert, where DataType is deduced as an integer, the compiler will emit code that treats m_item exactly as if it were an integer.

Then your question boils down to "What is an uninitalized integer initialized to"

int m_item;

Same as if you could call insert where DataType is of class A, the compiler will emit code that treats m_item as of type A, and your question is "What is an uninitialized variable of type A initialized to?"

A m_item;
Akill10 commented: Thanks +1
thelamb 163 Posting Pro in Training

In C++ NULL is defined as 0, so it won't make a difference.
(The use of NULL is even discouraged by some, including Stroustrup).

thelamb 163 Posting Pro in Training

Did you do a trace over or a trace into?
trace into should log everything.

To only log function calls you probably have to write a plugin for OllyDbg, I don't know of any existing way.

thelamb 163 Posting Pro in Training

Consider this:

HANDLE fHandle;

for( int i = 0; i < 7; ++i )
{
   fHandle = CreateFile( ... );
}

close( fHandle );

First time CreateFile is called, let's assume that fHandle will be set to 0x00000001. The next time it's set to 0x00000002, until 0x0000007.

After the loop, you're closing only the last handle (0x00000007), what happens to the other 6?
(They will be closed by Windows automatically when your program terminates, but it is very bad practice to leave them open.
So close the file handle when you're done with it, inside the for loop.

(In future please use code tags).

thelamb 163 Posting Pro in Training

Well, as you can imagine... if it were that easy it would've been built into IDA.

I do know of a 'run trace' in OllyDbg, if you use the latest version it is even quite fast (in 1.0 it's dead slow, especially if you 'trace into').
It can be a pain to analyze the trace log though.
Maybe it's also in IDA, but the debugger isn't very mature so I doubt the run trace would be better than in Olly.

Other than that... the only way I can think of is running the program in some virtualized environment which emulates all instructions and thus can log all calls, but I don't know if this is easily available anywhere.

thelamb 163 Posting Pro in Training

The program compiles, but doesn't do anything like I want it to

Help us out here:
- What do you want it to do?
- What does it do instead?

thelamb 163 Posting Pro in Training

A templated function doesn't _need_ to be defined in the header file, however it is usually easier to do so (see http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file ).

Inline functions however need to be in the header file, this has to do with 'translation units'. If you have an inline declaration in 'inline.h' and it's implementation in inline.cpp and then include inline.h in A.h, the definition of the inlined function won't be available to A.h because it is in a different translation unit.

Also note, when you define a function inside a class body it is automatically inlined:

struct test {
 void returnSomething() { return 1; }    // Implicitly inlined
 inline void definedElseWhereInHeader(); // Explicitly inlined
};

// This must still be in the header file
void test::definedElseWhereInHeader() { 
  // do something
}
Annettest commented: Thanks a lot theLamb. Very helpful answer. +2
thelamb 163 Posting Pro in Training

You're not actually modifying the inTables[q].Items in your first loop.

for each (AoE2Wide::DrsItem item in inTables[q].Items)
{
   // item is a copy of what's at inTables[q].Items, modifying item will leave the item in inTables[q].Items in tact
}
thelamb 163 Posting Pro in Training

I dont think you fully understand what templates are for, let's look at the name setter for example:

template <typename N>
N setName(N n)
{  
   Name = n;
   return n; 
}

Why do you need a template function here? Name is always a string.
So this would do just as well:

void setName(string n)
{  
   Name = n;
   //return n;  // Why do you need to return n? The caller already knows it
}

But now, every time you call setName( someString ); a copy is made of 'someString', so even better:

void setName( const string& n )
{
    Name = n;
}

Even this can be further 'optimized' if you call setName like: setName( "My New name" );
But let's not get too much into optimization 'details'

Read up on when and how to use templates ;)

thelamb 163 Posting Pro in Training

When you add a Looper, it is 'sliced' to it's base class.
What you need to do is store pointers or references to AudioTrackElement, they will 'preserve' the class hierarchy.

So:

AudioTrackElement* pNewEl = new Looper();
pNewEl->process( ... ); // calls Looper::process

delete pNewEl;
Looper newLoop;
AudioTrackElement newEl = newLoop; // Here it slices the object
newEl.process( ... ); // calls AudioTrackElement::process
thelamb 163 Posting Pro in Training

You can add an instance of a class just like any other variable:

class B
{
   int m_one;
   string m_two;
};
class A
{
   B instB;
};

Or if you just want a pointer to B:

class A
{
   B* instB;
public:
   A( const B& b )
   {
        instB = &b;
   }
};

Hope that is what you meant.

claudiordgz commented: Thanks!! +1
thelamb 163 Posting Pro in Training

It makes absolutely sense that this doesn't make sense at first sight ;).

void Reallocate(char* Source)

Here, Source is a _copy_ of char* Buffer. So modifying what Source points to will leave Buffer completely untouched.

Only if you modify the thing-that-Source-points-to you will also modify the thing-that-Buffer-points-to .. because they point to the same thing.

So essentially you have 2 pointers pointing to the same thing, and you modify what one of those pointers points to.


Change realloc to take a char** as argument, and hand over &Buffer, then you can modify what Buffer points to.

kerp commented: Thanks +1
thelamb 163 Posting Pro in Training

Look carefully at what it says: it says a 'const char*' was the reason of the termination, and you are catching 'char*'.

I guess the Microsoft compiler doesn't see that as a difference, and g++ does. So just change it to catch( const char* ).

Sorry I didn't spot this before... it is more correct to catch a const char*

thelamb 163 Posting Pro in Training

When you throw, the current function that's currently executing will end abruptly (it will not return though).

Then the exception will 'travel' back though the call stack, until it finds a catch block that catches it, when it finds one that catch block will be executed.
After the catch block is done, execution will continue normally starting from after the catch block.

void throwFunction() {
    throw( 5 );
    cout << "This will never be executed\n"; 
}

void callingFunction() {
    throwFunction();
    cout << "This will never be executed\n"; 
}

int main( ) {

    try {
        callingFunction();
            cout << "This will never be executed\n"; 
    } catch( char* str ) {
        cout << "Exception, str: " << str << "\n";
    } catch( int e ) {
        cout << "Exception, number: " << e << "\n";
    }catch( ... ) {
        cout << "Exception that's not an int or char*\n";
    }
}

throwFunction throws an int, so it stops executing. The exception travels back to callingFunction but there are no try/catch blocks around the call to throwFunction. So it travels back to main, where there are try/catch blocks.
It looks at the first block, which catches a char*... it skips this because the exception is an int. The next block catches an int, so that will be executed. After it prints "Exception, number 5" the execution will continue after the full try/catch blocks.

thelamb 163 Posting Pro in Training

Why do you catch in this function, immediately after you throw? If you remove the try catch in this function, you will have to catch it at the caller's side (and this function will not return). For example:

try {
 myHeap.top()
} catch( const char* e )
{
 cout << "Error: " << e << "\n";
}

I find it personally 'dirty' to throw a bare char*, I always create an Exception class which inherits from std::exception. And when I catch I catch a const std::exception&.

Edit:
if you want to catch in the top function AND make the caller catch as well, you can change the catch block in top to:

catch( const char* str )
{
   cout << ...;
   throw str;
}
thelamb 163 Posting Pro in Training

Don't include 'as soon as possible' in your topic and post... it is rude and even made me consider not replying to you at all.

You are defining the function SumN inside the body of main()... that is wrong. Each function must have its own scope.

Besides that, you say:
double* array;

*array;

that is also wrong... the type of array is double, not double*... Look up exactly how arrays work in C/C++.

General note:
'array' is a pretty bad name for a variable

thelamb 163 Posting Pro in Training

Tell us what you need to do please, without knowing some more details it's hard to suggest something.

thelamb 163 Posting Pro in Training

Here's a beginning:

int main( int argc, char** argv )
{

   return 0;
}

Now, please show some effort and actually _try_ for yourself. If you then have specific questions how to do something, ask again (and SHOW us what you have done yourself).

thelamb 163 Posting Pro in Training

C strings are 0 terminated, you are correctly creating the chars with size 81, and copying only 80 bytes to them, but what is the value of the last char? Exactly... it is garbage data.

So, you must initialize the char array to zero, you can do this in several ways:

char test[20] = { '\0' };
char test1[20];
test1[19] = '\0';
char test2[20];
memset( test2, 0x0, 20 );

I think this also answers your second question about str[0] = '\0'; ;), if not feel free to ask more detailed questions.

thelamb 163 Posting Pro in Training

Lastly, the function that takes "Test" I believe takes a slightly bigger datatype than const char* try prefixing it with L--

That depends if the OP is building with Unicode or multi-byte support.

Intrade commented: Very interesting. Thanks for correcting me! +2
thelamb 163 Posting Pro in Training

Next time also post the compiler error(s) you're getting ;)

thelamb 163 Posting Pro in Training

CreateThread doesn't take a pointer to a class's method, let's read the error message together:
Your argument type: 'DWORD (PMessenger:: )(void*)'
Expected arg type: 'DWORD (*)(void*)'

So CreateThread is expecting a pointer to a function that returns a DWORD and takes void* as argument. There are several ways to 'beat' this problem, because you cannot simply cast your function to a DWORD (*)(void*).

You can use a 3rd party library like 'boost', which allows you to use pointers to member functions to start a thread.
You can create a small 'wrapper' function like this:

DWORD start_ServerMsgThread( LPVOID param )
{
   PMessenger* pMsg = static_cast<PMessenger*>( param );
   pMsg->ServerMsgThread();
}

And start the thread like:

CreateThread( NULL, 0, &start_ServerMsgThread, static_cast<LPVOID>(this), 0, 0);

You hand over the SOCKET to ServerMsgThread, but you can just store this as a private member variable and access it from ServerMsgThread.
If you don't want to do this, you can create a structure with 2 members:

struct StartThreadStruct {
  SOCKET s;
  PMessenger* pMsg;
};

Allocate this, hand it over to CreateThread and from start_ServerMsgThread pass it to ServerMsgThread and access the SOCKET from there.

I hope that helps.

thelamb 163 Posting Pro in Training

Or look up the *_cast statements in C++.
e.g.
static_cast

thelamb 163 Posting Pro in Training

Any compiler will tell you that's wrong.
When you allocate an array statically(as oppose to dynamically) the size of the array _must_ be available at compile time. In your example, maxElements is a variable so the compiler has no idea if it's going to change at runtime.

So you have 2 options:
- allocate the array dynamically
- make maxElements a 'const int'

If you don't know how, ask ;)

thelamb 163 Posting Pro in Training

You can place the entire (nameless)struct's declaration in the class header.

e.g.:

class myWrapper
{
    struct 
    {
        int houseNumber;
    } address;

    public:
        myWrapper() { address.houseNumber = 555; } // this is valid
};

int main
{
    No way to access address from here, apart from a public interface.
}
thelamb 163 Posting Pro in Training

I've had the same 'problem' as you when I started (I'm also selftaught)... but I don't really understand what error handling has to do with it... but let me comment on that first:

You created your own macro that in debug-mode prints some information about the error.. this is a fine idea, you could also use assertations (lookup ASSERT). But in many cases, you also want to have some error-reporting in a release build.

I mostly use an exception class for this (CExcept), which inherits from std::exception. I overload operator<< in this class.
I can then do error checking:

void myFunction()
{
    if( hasError() )
        throw CExcept( SOME_EXCEPTION_ENUM ) << "myFunction failed horribly";
}

int main()
{
   try {

   } catch( CExcept& except )  // or std::exception& 
   {
        if( HORRIBLE_EXCEPTION_CODE == except.getCode() )
            err_out << except << "\n"; // in Debug build, this won't do anything
   }
}

err_out either functions as cout, or some file stream object or it could even be a class which emits the message as messagebox etc...
And it implements a << for ( err_out, except ) of course.

This way, if I want to change something as to how errors are handled in general I can do it in one place (Want errors to output to file? Just change err_out).
Also... a lot of functions set some error code (GetLastError in Windows or errno in Linux) with a simple #ifdef _WIN32 or #ifdef __linux__ in the overloaded …

thelamb 163 Posting Pro in Training

It is impossible to say how much faster your code wil run, if any faster atall, if you 'use vectors or pointers'. Generally using vectors will even be slower than using raw pointers.

I'm not sure how you expect to see a performance increase by using pointers... in certain areas using a pointer can speed something up, but it would probably be a better idea to look at your algorithm first (maybe even profile it to see where the bottlenecks are, if it's really that important).

Thinking about how many instructions your CPU is going to execute doesn't really have a lot of meaning, as Nathan mentioned a CPU can perform 2 billion instructions in a second but that says nothing about how many instructions your running process gets to execute, in fact it will probably not even run on the CPU consequtively for an entire second.

And as to your question regarding an instruction... the examples you mention like a file transfer could consist of thousands of instructions(and a lot of time waiting for the hardware, in which case the CPU can decide to calculate something for another process while waiting).

thelamb 163 Posting Pro in Training

A few things:

Why is 'item' in the test class public?
In your wrapper class you perform some operations twice:

string top(){
    item.top();
    return item.top();
}
// Why not:
string top(){
    return item.top();
}

Also, your push takes a string* as arugment, but it is not clear if 'push' is actually going to change something to the argument.

void push(string *ps){
    // It is possible to change the string here, for example:
    *ps = "Haha I changed your string!";
    item.push(*ps);
}

The user of your class normally has no idea how you implement your push, so a better approach is:

void push( const string& ps ){
        ps = "Haha I changed your string"; // <-- ERROR! ps is a const&
        item.push(ps);
    }

I assume you made it a pointer so that the string is not copied all the time, but if you use a reference(&) there also will be no copy.

thelamb 163 Posting Pro in Training

I think it's best you try and explain what you are trying to accomplish.
At the moment the use of strncpy isn't what it's intended for.

It seems to me you have a pollution_day array that you're trying to fill in the set_pollution function... but it's unclear what you want to fill it with.

In any case, you're kind of writing C code here (which can work of course but using C++ containers like vector may be much easier/more table ).

So if you give us some more details we may be able to help you come up with a better design.

thelamb 163 Posting Pro in Training

Good, then that makes it time to move away from the dirty C-arrays and use proper C++ classes. Show us how far you get ;)

thelamb 163 Posting Pro in Training

His approach isn't C-Style as the int i, ii; is not at the start of a scope block.
He does re-use the 'i' in two for loops, which is asking for confusion.

Anyway Ral78 what they are trying to point out is that it is good practice to make a variable's scope as short as possible (do you know what a 'scope' is?). So it is better to write code like:

for( int i = 0; i < n; ++i )
{
   // we can use i here
}
// here we can _not_ use i anymore

for( int i = 0; i < n; ++i )
{
  // Here we can use the new i again
}
// Nope, can't use i anymore
thelamb 163 Posting Pro in Training

First of all: Do you understand why there is only one beep and after that never again?

Secondly, let's think about your problem. You have an X number of objects(windows) and you want them to perform an action only once. So for each of these objects you can store a 'state' whether they have already performed the action or not.

Knowing this, what parameter/variable is unique for every object? This is a parameter that you can associate with the state variable.

In the end it comes down to storing the unique_object_identifier + state and searching for the unique_object_identifier in the TitleProc, to get the state and based on the state perform the action or not.

vadalaz commented: Thanks! +0
thelamb 163 Posting Pro in Training

webhost.com won't allow you to connect to the MYSQL database remotely.

Try to ping the domain:
C:\Users\thelamb>ping mysql9.000webhost.com
Pinging mysql9.000webhost.com [10.0.0.23] with 32 bytes of data:

10.0.0.23 is the local ip on 000webhost.com where they run the mysql server.

Kesarion commented: thanks +1
thelamb 163 Posting Pro in Training
void main()

Are you sure this is correct? If so.. why?

your enemy variable is a local, automatic variable. This means it will be destructed when it goes out of scope(do you know what a scope is?).

If you wish to delete the variable at some 'random' point in your code you need to ensure that it goes out of scope at this point OR you need to dynamically allocate the object.

Example:

int myFunction()
{  // start of myFunction scope
    int myInt;
    int* myDynamicInt = new int( 5 );
    while( true )
    { // start of while scope
         int mySecondInt;
    } // end of while scope (mySecondInt is destroyed here).

    delete myDynamicInt; // destroy myDynamicInt
}  // end of myFunction scope (myInt is destroyed here)

If you would have forgotten the 'delete myDynamicInt' in my example, it would cause a memory leak (myDynamicInt would never be cleaned up).

I hope that clears things up a little.

thelamb 163 Posting Pro in Training

You declare fgetline as a member function of the UTAevent class.
Except, when you define it you do not tell the compiler that the definition is part of the UTAevent class:

int fgetline(FILE *fp, char s[], int lim)
{
    // ...
}

Look at the other functions declared in UTAevent class, how are they defined in the .cpp file? What is the difference between those functions and your fgetline.

Salem commented: nice catch +21
thelamb 163 Posting Pro in Training

Absolutely not.. there is more wrong with declaring the variable on top than inside the for statement.

It's all to do with scope, if you declare the variable on top of the for loop, it is still in scope when the for loop exits, which is usually not what you want.

Declaring it in the for statement means the variable will go out of scope when the loop ends.

So declaring it on top, without using it anymore after the loop creates confusion for other people reading your code.

mrnutty commented: Exactly^2 +5
jonsca commented: Yes +4
thelamb 163 Posting Pro in Training

You have bigger problems than this...

void main() <-- really?

char *delim = ";"; <-- You need to learn what a pointer is, and how to use them, what you do here should ring a million alarm bells.

The error you are getting is because you are trying to assign a _char pointer_ to a char.

jonsca commented: Yes +4
thelamb 163 Posting Pro in Training

Ask yourself questions (before asking google). And be precise!
You did not read my last post fully, as the error I mentioned is still in. Don't just do something, hit compile and google for the errors you are getting, think structurally what you want to achieve, break the problem up in pieces and step by step take them down, making changes precisely and everywhere where you need to (declaration and definition should match).

After fixing what I mentioned, think about what input is.

thelamb 163 Posting Pro in Training

Encryption is not a matter of "read a book and you can write a quality encryption scheme" there are extensive subjects to the matter.

It is always dangerous as a non-encryption-expert to create a encryption scheme, just use an existing encryption library, and don't say it will be less secure because it is a popular library so a lot of people have already attempted/succeeded to crack it.

thelamb 163 Posting Pro in Training

By using your brain and thinking about the problem rather than asking how it is done.

As with any problem, try to break it up into smaller, easier pieces.
There is a string and you want to count the number of a's... in the real world, how would you do this if you had written the word on a piece of paper? Would you take a picture of the piece of paper and analyse the handwriting? Or would you simple read through the word, increasing a counter every time you see an a?

thelamb 163 Posting Pro in Training

That's not a question, that's "Can someone please do my homework". Which unfortunately no one is going to do for you.

So, as with many problems, the first step is: break it up in parts.
-> Do you know how to open a file?
-> Do you know how to read from a file?
-> Do you know how to use arrays?
-> etc.

Maybe even those questions you can sub-divide. Then take what you think should be the first step, and try to implement it. If you don't know how... google, if you tried something but it doesn't work.. post here and give us your thoughts (how do YOU think it should by done, and why do YOU think it fails)... then someone will help you out.

Fbody commented: right on :) +1
Ancient Dragon commented: Yes, that's what I meant too. +27