Tom Gunn 1,164 Practically a Master Poster

Can anyone give me some ideas on how to find the middle value between 3 numbers.?

Assuming it is always 3 numbers, and what you want is the median value, here is a simple way. Find the maximum then the minimum and the one you didn't pick is the median. :)

Tom Gunn 1,164 Practically a Master Poster

Typically the two options for a case like this are a count argument and a sentinel argument:

#include <stdio.h>
#include <stdarg.h>

/* gets a count of arguments */
void TestCount(int x, int n, ...)
{
    va_list args;

    va_start(args, n);

    printf("%d: ", x);
    while (--n >= 0) printf("%-3d", va_arg(args, int));
    putchar('\n');

    va_end(args);
}

/* gets a sentinel as the last argument to mark the end */
void TestSentinel(int x, ...)
{
    va_list args;
    int value;

    va_start(args, x);
    printf("%d: ", x);
    while ((value = va_arg(args, int)) != -1) printf("%-3d", value);
    putchar('\n');

    va_end(args);
}

int main()
{
    TestCount(0, 3, 1, 2, 3);
    TestSentinel(1, 1, 2, 3, -1);

    return 0;
}
Tom Gunn 1,164 Practically a Master Poster

..or may be I am missing some option, in witch case, it should be a lot more visible than it is... I couldn't find it ;-)

I can go to the Delphi forum, then under the Related Forum Features box on the right there is a direct link to all Delphi snippets.

Tom Gunn 1,164 Practically a Master Poster

Isn't it necessary to seed the random number generator if you want good results?

Not at all. The generator is seeded by default to a value of 1. It does not make the sequence returned by rand() any less random. The sequence is deterministic based on the seed, so every time the program runs with a default seed it will produce the same sequence. But the sequence itself is still pseudo random. :)

Tom Gunn 1,164 Practically a Master Poster

Can I enable/disable an #ifdef based on a specific condition?

Yes, but only if the condition is available at compile time. In your case the value of i is a run time quantity, so you cannot use it with the preprocessor. I think what you really want is an if statement:

for (int i=0; i<5; ++i)
{
   printf("Hello #%d", i);

   if (i == 3)
   {
      printf("I wanna be reached only if i == 3, is that possible?");
   }
}
Tom Gunn 1,164 Practically a Master Poster

Why would you consider not seeding the RNG here?

Why would I bother? It is an example program meant to show how the range of rand() can be shifted using modulus. Adding unnecessary code will only muddy the waters.

Tom Gunn 1,164 Practically a Master Poster

Forgot to seed.

You presume that seeding is a required step, which it is not. Design choices are not the same as memory lapses. ;)

Tom Gunn 1,164 Practically a Master Poster

The simplest way to adjust the range of rand() is with the modulus operator:

#include <iostream>
#include <cstdlib>

int main()
{
    for (int x = 0; x < 20; ++x)
    {
        std::cout << (std::rand() % 900 + 100) << '\n';
    }
}

I am sure someone will chime in with the multitude of problems that this solution has, but if you need to worry about those problems, rand() is not the right random number generator for your application. :)

Tom Gunn 1,164 Practically a Master Poster

Some of the tokens are being stored with blank spaces proceeding them.

That sounds like you need to skip leading whitespace at the token level. When resetting start, instead of incrementing it, walk it over all whitespace. The following is a stream of consciousness. It is meant to spark your imagination, not to be an actual plugin for your code:

// start = (finish != string::npos) ? finish + 1 : string::npos;
if ((start = finish) != string::npos)
{
    while (start < str.length() && isspace(str[start])) ++start;
    if (start == str.length()) start = string::npos;
}
Tom Gunn 1,164 Practically a Master Poster

where is this function and how is it called ?

It is done by the C runtime. The same code that calls main() collects arguments from the command shell and parses them into an array of char pointers.

Tom Gunn 1,164 Practically a Master Poster

Should I put delete in the constructor of that class

The destructor, yes. Or better yet, use a smart pointer like auto_ptr where you do not need to worry about deleting it at all.

Tom Gunn 1,164 Practically a Master Poster

So at what point I have to delete this pointer?

As long as you have a copy of the pointer that was returned by new , you can delete it. You said that the pointer is stored in another object, so that object's destructor would probably handle the deletion. Though that is not exactly the best design, IMO.

Tom Gunn 1,164 Practically a Master Poster

There are left over characters in the stream that cin.get() is reading immediately. It is not blocking, so the program ends immediately and I assume the window is closing so you cannot see the output. Try this:

#include <iostream>
using namespace std;

int main()
{
    int length; // this declairs a variable
    int width; // this declairs another variable

    cout <<"Enter The Length: ";
    cin >> length; //input the length

    cout << "Enter The Width: ";
    cin >> width; //input the width

    cout <<"The area is: ";
    cout << length * width; //display the area

    cin.ignore(1024, '\n');
    cin.get();

    return 0;
}

I added the cin.ignore(1024, '\n'); line. 1024 is an arbitrary large value because I did not want to scare you with the more correct numeric_limits<> construction. ;)

Tom Gunn 1,164 Practically a Master Poster

I just cant seem to fathom the last part of each line is being completely ignored...

I know the answer to this problem because it is a problem I create myself on a regular basis. :) On the last token, finish will be string::npos . After the last token, start should be string::npos so that you do not lose the last token. That means the loop should test on start , and you need to take care not to wrap beyond npos :

start = 0;
finish = tempToken[ x ].find_first_of( " ", start );
while( start != string::npos )
{
    tokens[ y ].tokenString = tempToken[ x ].substr( start, finish - start );
    tokens[ y ].lineNumber = x + 1;
    start = (finish != string::npos) ? finish + 1 : string::npos;
    finish = tempToken[ x ].find_first_of( " ", start );
    y++;
}
Tom Gunn 1,164 Practically a Master Poster

does it chooses the multipales randomly ?

IIRC, the architecture's page size is the determining factor for the file and section sizes.

also for pe files in memory version is aligned to 0x100 wouldn't that make program bigger in memory than in file ?

The section alignment can be the same as the file alignment or bigger. If it is bigger, then more padding is used in memory, which can be used for data storage.

Tom Gunn 1,164 Practically a Master Poster

getch();

This may or may not work. getch() is not a standard function and not all compilers implement it as an extension. If the only goal is to keep the window open, any blocking read will do:

#include <iostream>

int main()
{
    std::cout << "Hello world!\n";

    // blocking read to keep the window open
    std::cout << "Press [Enter] to continue";
    std::cin.get();
}

This program is portable because cin.get() is a standard method with well defined behavior.

Tom Gunn 1,164 Practically a Master Poster

Yes, null bytes with a value of 0x00 are used as padding for alignment purposes.

Tom Gunn 1,164 Practically a Master Poster

A stringstream is still a stream, and stream objects in C++ do not have copy semantics. You can make that field a reference or a pointer if the stringstream is a necessary instance variable. Or you can recreate the stream each time you need it, but that would depend on what you are using the stream for.

necrolin commented: You're a life saver. Thank you. +1
Tom Gunn 1,164 Practically a Master Poster

Can you post the definition of the Client class? It looks like the problem is a field that does not have copy semantics, and the vector class requires those semantics.

Tom Gunn 1,164 Practically a Master Poster

What do you mean by "it's not working"? Are you getting a compile time error? A run time error? "It's not working" is not a helpful description of the problem.

Tom Gunn 1,164 Practically a Master Poster

how can I restrict that this function has to be member of a specified class only?

You can remove the template and use a specific class if there is no need for generality:

real Integral(myclass& obj, real (myclass::*func)(real), real lower_bound, real upper_bound)
{
    //...
}

Are there any solution in which
you not must to type the same code twice,
and it can act on normal and member functions too?

Not without being convoluted. The usage of normal and method pointers are different, so at the point of the call you need at least a specialization. You can pass that in as some variation of the strategy pattern, but it would probably be simpler to have two interfaces and one implementation if your integral algorithm does not need to call the pointers internally.

This is wrong! How can i use "this"?

this is a pointer, but Integral() takes a reference to an object. You need to dereference this first:

return Integral(*this, &myclass::func1, a, b);
Tom Gunn 1,164 Practically a Master Poster

Why do you write:
template <typename ClassType>
why not:
template <class ClassType> ?

Personal preference. They both mean and do the same thing in this case. I use typename instead of class because it makes me look like a hip C++ guru who is down with the latest language standard. ;)

It is not possible to solve this with only one "function identifier" parameter passing to the Integrae function?

Maybe. It really depends on what myclass::classfunction() is supposed to do. If it modifies the state of an object and you want to keep that modification, you need some way of passing or returning the object that the method pointer is called on. Otherwise you can create a dummy object in the Integral() function, call the method pointer on it and throw it away. But then I would ask why you want to use a method pointer in the first place when it makes no difference. :D

Tom Gunn 1,164 Practically a Master Poster

Yes it is. But it is also called C++Builder, not Turbo C++.

No, I was wrong. Turbo C++ 2006, also called Turbo C++ Explorer, is not available anymore. It looks like the only free option now is a trial version of C++ Builder.

William was advising against the use of Turbo C++, not C++ Builder and they are not the same thing.

I know what William was advising against, but for the last few years Turbo C++ had been resurrected as Turbo C++ Explorer, with the 2006 version of Borland's compiler. I saw it the same as condemning VS2008 based on the problems of VS6, so I was making sure that everyone knew a more recent version of Turbo C++ was available. But I was wrong and that version is not available anymore, so it is safe to assume any mention of Turbo C++ means the ancient versions.

I apologize for giving outdated information. It was accurate when I checked a few months ago, and I made an unwarranted assumption that it was still accurate.

Tom Gunn 1,164 Practically a Master Poster

Pointers to functions and pointers to methods are not the same thing. A pointer to a method is really an offset into the class, not a real pointer with an address value. You need to make two overloads of the Integral() function. One that takes a function pointer and one that takes a method pointer:

#include <iostream>

typedef double real;

real Integral(real (*func)(real))
{
    return func(0);
}

template <typename ClassType>
real Integral(ClassType& obj, real (ClassType::*func)(real))
{
    return (obj.*func)(0);
}

class myclass{
public:  
    real classfunction(real);
};

real myclass::classfunction(real x)
{
    return 3.14;
};

real myfunc(real x)
{
    return 1.23;
}

int main()
{
    myclass probe;

    std::cout << Integral(myfunc) << '\n'
              << Integral(probe, &myclass::classfunction) << '\n';
}

An extra complexity with pointers to class members is that the pointer is defined on the class, but to use the pointer you need an object of that class to access the member. That is why the Integral() overload for the member pointer also has an argument for an object of the class type.

Tom Gunn 1,164 Practically a Master Poster

when you load executable does it load directly in RAM or it gets loaded in hdd and sent to pages to hdd

Executables are loaded into memory. Memory could mean either physical memory or virtual memory. If you open more programs than the physical memory can handle, the computer will start paging in and out of virtual memory. The whole point of virtual memory is to extend the physical memory without anyone being the wiser. The cost of that extension is speed, which brings me back to the statement of anything that uses memory can potentially cause thrashing.

Tom Gunn 1,164 Practically a Master Poster

One thing that causes thrashing is when physical memory is filled up and spills over into virtual memory. Virtual memory is disk based instead of RAM based, so it is much slower to access data stored in virtual memory. Anything that uses RAM can potentially cause that form of thrashing.

let's say we load many files at once wouldn't that cause thrashing ?

It depends on how the files are loaded. If they are large and completely stored in memory all at once, that could easily cause thrashing. If they are small or the program loading them is smart enough to conserve memory, thrashing is not as likely.

Tom Gunn 1,164 Practically a Master Poster
main()

If you do not specify a return type for main(), it does not mean you are exempt from returning a value. This feature is called implicit int. It means that if a data type is expected but not provided, int is assumed. So these two definitions of main() are exactly the same and the return statement is required for both:

main()
{
    return 0;
}
int main()
{
    return 0;
}

Relying on implicit int is not a good practice because the latest C standard removes the feature. Your code will not compile as C99, and that adds one more thing that needs to be changed to make it conform.

char STR1[100];

Names in all upper case are usually reserved for macros. It is up to you whether or not to use that convention, but people reading your code will be confused that STR1 is an array object and not a macro.

clrscr();

clrscr() is a non-standard function from conio.h, but you did not include conio.h. I would not recommend anything from conio.h, but like the naming conventions, it is up to you whether or not to take that advice. The portability police will not haul you away if you choose to use unportable stuff. :)

gets (STR1);

gets() is always unsafe and cannot be made safe through good coding practices. Never use it, because there is always a risk of array overflow. The safe alternative to gets() is fgets():

Tom Gunn 1,164 Practically a Master Poster

I cant use while ...

i should do it with if -else only ..

any suggestions ??

If the number of substances in the file is fixed, you can unroll the loop because the logic inside the loop is what you want for getting the right output. The loop itself just makes the code shorter and easier to follow.

Tom Gunn 1,164 Practically a Master Poster

I think your approach is better if you add line breaks, but you can probably get the right output like this:

open file
let n be 1

while more substances
    read a substance

    if substance freezes
        print name + " freezes"
    else if substance boils
        print name + " boils"
    else
        continue

    if n++ is even
        print line break
    else
        print " and "
end while

close file
Tom Gunn 1,164 Practically a Master Poster

i tried to solve it but i couldnt get the same input ..

Post your try and we can help you make it better.

Tom Gunn 1,164 Practically a Master Poster

It's ancient and there's just so many reasons to use an up-to-date compiler, can't be bothered listing them.

For several obvious reasons Tom Gunn :

1)Because it is sub standard.
2)Uses all the extinct headers and commands.
3)It is not according to the c99 standards.
4)void main is valid in it.
5)The blue screen irritates a lot...
And loads other stuff.........

That is what I thought you were going to say. Please check your facts before turning people off to a good compiler. Turbo C++ has an up-to-date version from around 2006. As far as I know, it conforms to the standard. If you are going to bash Turbo C++, at least make it clear what version you are attacking and why.

Tom Gunn 1,164 Practically a Master Poster

Don't use Turbo C

Why not?

Tom Gunn 1,164 Practically a Master Poster

You differentiate between logical and actual links. Logical links are part of an n-ary node, but represented with actual binary links. If you can do that, you will be able to figure out how to move when doing any traversal. Red black trees do this well, if you need a real world example. Red links are logical links and black links are actual links, and they come together to represent a 2-3 tree with a binary structure.

Tom Gunn 1,164 Practically a Master Poster

Replace this part of your header:

#define N_GLAC=22;
#define latGLAC[22] = {43.96875, 45.34375, 45.34375, 46.15625, 46.21875, 46.28125, 46.78125, 46.84375, 46.84375, 46.84375, 46.90625, 47.46875, 47.53125, 47.78125, 47.78125, 48.03125, 48.03125, 48.59375, 48.78125, 48.78125, 48.96875, 51.46875};
#define lonGLAC[22] = {-110.84375, -121.65625, -121.71875, -121.46875, -121.53125, -121.84375, -121.71875, -121.65625, -121.71875, -121.78125, -121.78125, -120.84375, -121.21875, -123.65625, -123.71875, -121.09375, -121.15625, -113.71875, -121.34375, -121.84375, -114.21875, -117.78125};

With this:

#define N_GLAC 22
double latGLAC[22] = {43.96875, 45.34375, 45.34375, 46.15625, 46.21875, 46.28125, 46.78125, 46.84375, 46.84375, 46.84375, 46.90625, 47.46875, 47.53125, 47.78125, 47.78125, 48.03125, 48.03125, 48.59375, 48.78125, 48.78125, 48.96875, 51.46875};
double lonGLAC[22] = {-110.84375, -121.65625, -121.71875, -121.46875, -121.53125, -121.84375, -121.71875, -121.65625, -121.71875, -121.78125, -121.78125, -120.84375, -121.21875, -123.65625, -123.71875, -121.09375, -121.15625, -113.71875, -121.34375, -121.84375, -114.21875, -117.78125};

There were two problems. First is you were defining N_GLAC the wrong way for a macro. Macros do not use the = sign to assign a value, and they do not end with a semicolon. Second, you were trying to define arrays with macro syntax. A header is nothing special when it comes to defining objects. You do it the same way as any global variable.

vaishnavi_5 commented: I tried to const uint16_t Cos12bit[361] = {4000,....}; with 361 elements in main.h but it shows error as duplicate definition in main.o & stm32f30x.o +0
Tom Gunn 1,164 Practically a Master Poster

Is that simply what I must do or is there a way to make it so the two functions have the same name?

There is a way, but it means writing a dispatch function or macro and all of the complexity involved. It is pretty simple if you are working with a small number of known functions, but something generic will probably be hairy. It is easier and probably better overall to avoid all of those moving parts and just use different names for each function. ;)

Tom Gunn 1,164 Practically a Master Poster

It is impossible to help you without seeing the code that your compiler balks at and the errors that are thrown. Please post all of your code, or a small self-contained subset that has the error, and post all of the errors you get.

Tom Gunn 1,164 Practically a Master Poster

There are different iterator categories. The iterators for a vector are the most flexible and they are called random access iterators. Lists use bidirectional iterators, and those do not support comparing with less.

Tom Gunn 1,164 Practically a Master Poster

So what is the problem?

Tom Gunn 1,164 Practically a Master Poster

int array[4] = {1,2,3,4}; will work, but putting objects in headers is generally a bad idea because it is easy to accidentally define the object multiple times just by including the header more than once. Inclusion guards are only a partial fix for that problem.

Can you be specific about how the code you have tried does not work?

Tom Gunn 1,164 Practically a Master Poster

Just curious, what do you think C++ does when it passes by reference.

I think the easier implementation would pass by pointer and hide the pointer mechanics on the compiler side. A more "pure" implementation of references might somehow mark the reference and replace it with the same address as the original variable when generating machine code. That is neither here nor there as this is the C forum. :)

You said pass by reference doesn't copy the value or the address of the data.

Not so. I said something more general because C does not have native pass by reference semantics:

pass/call by reference uses the same object that was passed as an argument

How the same object is used is an implementation detail, and the detail does not matter as long as the effect of pass by reference is achieved without programmer intervention.

The programmer intervention part is why I do not believe C supports pass by reference. If I need to do something special beyond declaring a reference, the effect of pass by reference is not fully achieved. With pass by pointer I need to assign the address of the object before calling the function and I need to dereference the pointer to get to the object inside the function.

Tom Gunn 1,164 Practically a Master Poster

Is pass by value and call by reference the same?

No. Pass/Call by value makes an independent copy of the value for use in a function, but pass/call by reference uses the same object that was passed as an argument. Everyone likes to keep saying it, but C does not have pass by reference. It can only be faked passing pointers by value and using indirection them to get the original object.

why do we use call by value and pass by value? what are its uses?

Here is a 10,000 foot overview. Use pass by reference when:

  • The object is very large and passing it by value would be costly for memory. Make it const if it should not be changed.
  • The original object needs to be changed within a function and cannot be used as a return value.

Use pass by value when:

  • The value is small and the original object does not need to be changed within a function.

In the context of C, 'pass by reference' really means 'pass a pointer by value'. The whole thing is kind of a solved problem because C is such a small language. You either pass a pointer or not, depending on your needs. I think a more interesting question is whether or not value parameters should be made const:

void Function1(int x, int y);
void Function2(int const x, int const y);

But that is too far off topic for the thread. …

Tom Gunn 1,164 Practically a Master Poster

However, my integer to hex function gets stuck in an infinite loop and I have no clue why.

You never change the value of number inside the loop. The algorithm should be dividing it by 16 and storing the result, right? Also, 0 and '0' are two completely different values. Be sure to double check whether you are working in a string context or a numeric context and use the right constants.

n = number;

This will probably give you problems as well. The expression should be the other way around because number is the variable you are trying to initialize.

Tom Gunn 1,164 Practically a Master Poster

but aren't RVA is on load time ? so code will be build but will crash ?

RVAs are converted to real addresses when the PE is loaded into memory by combining the PE base address with the RVA. The RVAs themselves are generated at build time for the executable. What happens depends on whether or not an overflow test is in place. If it is in place, the code will fail to build. If it is not in place, the code would probably build and load, but exhibit unpredictable behavior because the DWORD wrapped around and two variables have the same address. I have never heard of either problem happening, and that is why I think it is so rare as to be a non-issue.

Tom Gunn 1,164 Practically a Master Poster

RVAs work like the segmented addresses. In the segmented memory model you have segments and offsets that combine to give the final address. An RVA is the offset that is combined to the PE's base address when loaded into memory.

what if there are many temperoralily variables wouldnt that overflow the that RVA value or i got the concenpt of RVA values all wrong ???

I do not know the answer, but if you use enough RVAs at the same time to fill up a DWORD without running out of some other critical resource first, I assume the code will not build. I do not think this is a risk that you should worry about.

Tom Gunn 1,164 Practically a Master Poster

1. Concept of Late binding can be acheived by Function pointers or indirect calls - This is due to the fact that compiler cannot simply substitute the address of the function when it encounters a function pointer, instead it needs to dereference it at a later stage.

That is my understanding too.

2. But in case of c++ compiler will associate a VPTR which points to a VTable while declaring a class when it encounters a virtual function.

Yes. The C++ compiler can generate and assign vtable addresses at compile time, but in C I did it manually for the vtable implementation and picking the vtable for new objects. The virtual method implementation was meant to show that even in C++ there is nothing special about methods. Internally they will probably be nothing more than regular functions with a special naming scheme that ties them to the class, like __Base_void_ToString_void corresponding to void Base::ToString() . If it is a virtual function, instead of using an inline definition, it just makes a call into the vtable using the index of the actual method definition.

My virtual method definition is the end result after an imaginary C++ compilation phase. Think of the original as this:

struct Base
{
    int _x;

    virtual void ToString()
    {
        //...
    }
};

First the method is hoisted out of the struct and made a traditional function with the mangled name and taking this as the first argument:

struct Base
{
    int _x;
}; …
Tom Gunn 1,164 Practically a Master Poster

Here is a simple example of one way to implement vtables in C:

#include <stdio.h>

/* class definitions */
typedef struct Base
{
    void (**vtable)();
    int _x;
} Base;

typedef struct Child
{
    void (**vtable)();
/* begin base class slice */
    int _x;
/* end base class slice */
    int _y;
} Child;

/* class method implementations */
void Base_ToString(Base const* obj) { printf("Base: (%d)\n", obj->_x); }
void Child_ToString(Child const* obj) { printf("Base: (%d,%d)\n", obj->_x, obj->_y); }

/* vtable implementation */
enum { Call_ToString };
void (*Base_Vtable[])() = { &Base_ToString };
void (*Child_Vtable[])() = { &Child_ToString };

/* virtual method implementation */
void ToString(Base const* obj)
{
    obj->vtable[Call_ToString](obj);
}

int main()
{
    /* pick the vtable for objects at compile time */
    Base base = {Base_Vtable, 123};
    Child child = {Child_Vtable, 456, 789};

    Base* a = &base;
    Base* b = (Base*)&child;

    /* call the virtual methods */
    ToString(a);
    ToString(b);
}

I did not include any code for handling multiple inheritance. That is harder to do. The implementation does not matter as long as the end result is the effect of late binding. Even vtables are not required, but it is a common implementation in C++ compilers.

Note: This example is not completely portable, but neither is a compiler. ;)

Tom Gunn 1,164 Practically a Master Poster

I have no idea for what I should use this (size_type) parameter.

If your allocator does not need it, do not worry about it. The allocator interface was designed to be generic, and some allocators will need that information to manage the memory. For example, moving blocks from a 'used' pool to a 'free' pool means knowing how many blocks to move. Or more simply, the size could be used for debug information.

Tom Gunn 1,164 Practically a Master Poster

Please post your code and the errors.

Tom Gunn 1,164 Practically a Master Poster
void CPU::setType(string newType);
{      
       type = newType;
}

Above is an example of the problem. Look for the extra semicolon after the parameter list. That should not be there either. Rinse and repeat for all of your method definitions. And be careful when copy/pasting declarations and turning them into definitions. I accidentally copy the semicolon a lot too. ;)

Tom Gunn 1,164 Practically a Master Poster

In CPU.cpp, remove public from all of the method definitions. C++ does not work like Java and C#, where the access level is applied to each entity.