deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For the most part, whitespace in C is ignored. All three of your examples are functionally identical. You could also say const char*buf and it'll work fine because the tokens aren't ambiguous. However, constchar won't work.

Another bit of trivia is that const doesn't have to go before the type: char const *buf. This can make declarations easier to decipher as they're typically read inside out and right to left: char const * const buf reads as "buf is a const pointer to const char".

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

We already have a chat feature. On the footer bar you'll find one quick way to get to it (the Chat button).

diafol commented: he heh - that was quick action! +14
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The character(s) pointed to by buf are treated as read-only. To make the pointer itself const, place the keyword after the asterisk:

char * const buf;       // const pointer to non-const char
const char *buf;        // Non-const pointer to const char
const char * const buf; // const pointer to const char
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There is no distinction between an array and a pointer this (1st) case.

Yes, that's close enough.

It looks like as if p is hidden array of pointers.

No, it's just a pointer. Since it points to the address of an item in an array, you can treat that pointer like an array to get other items. The concept here is that pointers give you largely unrestricted access to memory. If a char pointer (call it p) points to address 12345, you can use *(p + 1) to get the value at address 12346. Because array indexing is just syntactic sugar for pointer arithmetic, that means you can also say p[1] for the same effect.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

C99 concept of variable array is not accepted in Recent Compilers .They give errors like" Constant Expressions required in Function main on line 9"

Then you're not compiling as C99. The compiler also must support C99, which not all recent compilers do. Further, it looks like you're using Turbo C, which is not a recent compiler by any measure.

However, that said, I don't recommend this feature even if it's supported (for various reasons I won't elaborate on unless asked). I'd recommend using a pointer and dynamic memory allocation.

But after little modification Every thing went correctly by Initializing a dummpy value to an array and making it as global.

Your code is broken. At the point of the array definition, n is uninitialized, which invokes undefined behavior.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your code is still broken. A correct variation would be:

int a[2][3] = {{8, 9, 10}, {11, 12, 13};
int *p = a;

printf("%p\n", p[1]); // Prints the address of a[1]
printf("%d\n", *(p[1] + 1)); // Prints 12

p in this case points to the first row of a. It can be indexed to get to subsequent rows or using pointer arithmetic.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What I meant to say is 'p' is declared as Pointer Variable and not Array of Pointers, so as to point to multiple variables.

A pointer is just a pointer. It points to a single entity of the declared type, but using pointer arithmetic can traverse over multiple entities if they exist. Is that what you're asking?

It works fine my friend.

"Works" and "correct" are two different things. Just because something works doesn't mean it'll always work. Predictable, portable behavior is the key for correctness.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

void Change_Address( int *&p, int *&pt)

That's C++, not C.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is there any place I can read more about this type mismatch.

Click Me.

It looks like as if p is hidden array of pointers and it is declared by default as p is assigned address of an array. Is it so ?

I'm having difficulty deciphering that question, can you rephrase it for me?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

*p=&a or *p=a will assign base address to p, which is equivalent to *p=&a[0].

Type matters, even if the addresses are all the same. *p = &a assigns a pointer to 2D array (ie. int(*)[2][3]) to a pointer to int, thus a type mismatch. *p = a assigns a pointer to a 1D array (ie. int(*)[3]) to a pointer to int, also a type mismatch. Only *p = &a[0] will do what you want, which is assign a pointer to int to another pointer to int.

So p[4] is same as *(p+4) ?

Yes.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

*p=&a is a type mismatch if you want to flatten the array. Try *p = &a[0] instead. Also note that this trick isn't strictly portable due to how C restricts pointers walking past the end of an array. It'll work on every implementation I'm aware of though.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

malloc, realloc, and free. You have control over how much memory is used at any given point, but that control comes at the cost of managing allocations. The starting point would be:

char *p = malloc(4);
strcpy(p, "ABC");
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The last two would be recommended for not wasting memory. However, there are two questions that determine which you use, or if you want to go with dynamic memory allocation instead:

  1. Do you intend to modify the string?
  2. Do you indend to grow the string or is the size fixed?
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Any solution to this problem other than separately evaluating expressions ?

Nope.

What does it mean by "all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed." ?

Side effects are things that happen beyond the direct result of the expression. As an example, a side effect of calling printf is that something gets written to the screen. A side effect of --a is that a gets decremented.

One of the reasons for sequence points is to have a consistent place at which you an say that side effects for an expression have completed. The canonical sequence point is the semicolon that terminates a statement.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But, dosen't post increment supposed to hold its concept for every kind of compiler ?

Yes. The problem is that the compiler can reorder and change expressions between sequence points however it wants as long as the defined behavior isn't affected. One possible ordering of c=(--a)+(--a); might be:

--a;
--a;
c = a + a;

Other equally rational orderings and changes are possible, which is why multiple updating side effects on an object in an expression is undefined.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Someone please point out where is loophole in my knowledge.

The missing link is sequence points and undefined behavior. In c=(--a)+(--a);, a is being modified multiple times between sequence points, which invokes undefined behavior. The compiler is under no obligation to do anything predictable.

Your second attempt removes the undefined behavior, and thus it works as expected and predictably.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

can you explain to me how the find_if works?

It works exactly like find, except instead of comparing against a value, it calls a predicate (in the form of a function, function object, or lambda). This gives you more flexibility in customizing exactly how you want the values in the vector to be compared.

I still dont understand it quite well

Will a definition help? find_if works like this:

template <typename InputIter, typename Pred>
InputIter find_if(InputIter first, InputIter last, Pred compare)
{
    while (first != last)
    {
        if (compare(first))
        {
            break;
        }

        ++first;
    }

    return first;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Two options. One is a verbatim string:

var query = @"select beggining_school,
end_school FROM Student,student_weekend,Weekend WHERE 
Student.ID=student_weekend.studentID AND 
student_weekend.WeekendID=Weekend.ID"

Note that indentation is significant in the string, as are newlines. The other, my preference, is literal concatenation because there aren't any "hidden" characters:

var query = 
    "select beggining_school," +
    "end_school FROM Student,student_weekend,Weekend WHERE " +
    "Student.ID=student_weekend.studentID AND " +
    "student_weekend.WeekendID=Weekend.ID"
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Did you terminate your Salaried class with a semicolon?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I can't figure out how to clear the "MathDep" - previous collection of items before importing the collection of items again.

MathDep.Clear()

Since you're using a hardcoded collection, you can just clear MathDep when you clear ListBox1.Items.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Let's start with one quick clarification, XML is a text format. So technically you can save XML to a .txt file. ;)

I just can t see xml being a advanced technology for data saving and transportation.

That's because it's not. XML isn't the most human readable format out there, and it's very verbose. The cost of formatting versus actual data is high enough that you could describe XML as a wasteful text format.

On the other hand, XML is well known, very well supported by libraries and utilities, and an integral part of the .NET framework (think configuration files).

they always lack to provide an EXAMPLE WITH SOMETHING ELSE

I'm not sure why you would expect them to, unless they're arguing in favor of another format. In my experience, delimiter separated formats are the most common alternative to XML, but they tend to be less flexible.

castajiz_2 commented: tnx. +3
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This is a quirk of the C++ object model. Since the member function isn't virtual, the compiler knows exactly what function to call and doesn't depend on the object instance being valid. Technically, all non-virtual member functions are shared under the hood (virtual member functions work through a lookup table stored in the object). When you say a->func(), the generated code looks more like this:

struct A
{
    int _dmember;
};

void __class_A_12345_func(A *self)
{
    cout << "Inside A!! " << endl;
    cout << self->_dmember;
}

...

int main()
{
    A *a = NULL;

    __class_A_12345_func(a);

    return 1;
}

Given a low level view of how things are set up, it's easy to see how a->func() will work just peachy when a is a null pointer. However, the problem is inside the function where you request the value of an instance data member, which invokes undefined behavior because a is a null pointer. I'd expect a crash at that point, but your compiler may generate code that supresses it for this case. Regardless, the code is broken because the function tries to access something that relies on a valid instance.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you don't add any code to the event handler, simply resetting it in the control properties will delete the code as well. If you do add code (even if you delete it immediately), the best approach is to delete the handler manually and also reset it in the control properties.

If you want to go full manual, you can find where the handler is attached in your compiler generated code and remove that rather than do it from the designer.

castajiz_2 commented: TNX! +3
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In your debugger, copy the contents of sqledit and run the query manually from your database. This makes it easier to spot check queries because it eliminates the obscuring of issues through VB.NET boilerplate.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

then why when I run program all I get is endless 0's ?

Simple math says that many of the cells will contain 0 since x, y, or z will be 0, and 0 times anything results in 0. However, there's a bug in the code:

for (int y = 0; y<dimy; dimz++)

Notice the increment step modifies dimz rather than y.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What's the value of x? Neither of the values in notename suggest a valid file name, and if they do, you'd need to verify that the file is in the current working folder. I'd suggest trying perror to get more information on why the file didn't open successfully:

if (!readnote)
{
    perror("Read Error");
}

You can find perror in stdio.h.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

As long as they do not begin with numbers. Is this standard functionality?

Yes.

but then it is rather vague about what identifiers are, exactly.

You might be reading the wrong section. Section 2.11 (C++ n3242) gives both a grammar and a detailed description of syntax. Section 6.4.2 (C99) is equally detailed.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I am a programmer. That's why I'm receiving a paycheck. I sit alone in a small cubicle and do my work.

That's an interesting description of a programmer. I wish I could sit alone in my office and do my work without having to communicate with the rest of my team or end users, but that's not realistic. ;)

So my boss says to me today that I am being signed up for a FIVE day course in..... Microsoft OUTLOOK.

Unless the training involves teaching a component that you wrote, I'd agree that it's outside the scope of your job description as stated. That's not to say that your boss doesn't have a different idea of what your job description is, so the first step would be to get clarification and work from there.

If you're a programmer like me, what would you do?

I'd probably do it for the experience and to help out the users, but make it clear to my boss that this is outside the scope of my job description. I might also try to negotiate a bonus of some sort and have my boss handle scheduling and schmoozing of lost time for the days I wouldn't be doing the job I was hired for.

The last thing you want is to be punished for doing what was asked of you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

because the MSDN program still uses errror.h, and hendels the error in old fasion way!

You mean errno.h? _stat and FindFirstFile are both C-based API functions, so errno and return codes are essentially the only option for handling errors. You can wrap your own exception handling mechanism around it if you really want to, but the "old" way doesn't mean that it's not functional or effective. ;)

#include <errno.h>
#include <exception>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>

using namespace std;

class StatException : public exception
{
    string _message;
    string _filename;
public:
    StatException(const string& message, const string& filename)
        : _message(message), _filename(filename)
    {}

    const char *what() const { return _message.c_str(); }
};

class FileStat
{
    struct _stat _buf;
public:
    FileStat(const string& filename)
    {
        if (_stat(filename.c_str(), &_buf))
        {
            switch (errno)
            {
            case ENOENT: throw StatException("File not found", filename);
            case EINVAL: throw StatException("Invalid parameter", filename);
            }
        }
    }

    _off_t Size() const { return _buf.st_size; }
};

int main()
{
    try
    {
        FileStat stat("test.txt");

        cout << "Size: " << stat.Size() << " bytes\n";
    }
    catch (const StatException& ex)
    {
        cerr << ex.what() << '\n';
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

A control can be a container for other controls, so such an algorithm should be recursive:

Private Sub SetControls(ByVal Control As parentCtrl)
    If TypeOf parentCtrl Is Label Then
        ' Set the label properties you want
    End If

    For Each ctrl As Control In parentCtrl.Controls
        SetControls(ctrl)
    Next
End Sub
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I've noticed that when generating random numbers they repeat.

It sounds like you want a random shuffle rather than a random selection. The former will give you a randomized ordering of the set such that there are no repeats until the set is exhausted:

// Untested code
var rand = new Random();
var to_eat = from x in fruits
             order by rand.Next()
             select x;

foreach (var fruit in to_eat)
{
    Console.WriteLine("nom nom " + fruit.Name);
}

Random doesn't mean "no number will be repeated", it means the sequence of numbers will be suitably unpredictable.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Code highlighting doesn't run after a post is submitted. If you reload the page, your code will be displayed with highlighting.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just the function or member function name won't do, the argument list is required even if it's empty. For example:

obj2->Landline(); // Notice the parentheses

Also note that you'll immediately get a runtime failure because obj2 doesn't point to anything. Either make it a regular object:

PCTL obj2;

...

obj2.Landline();

Or have the pointer point to an object:

PCTL base_obj;
PCTL *obj2 = &base_object;

obj2->Landline();
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The thumbnails still take up contiguous memory. Usually when you get an out of memory exception in image processing, it's due to fragmentation. Have you considered using a window of the thumbnails rather than trying to display all of them? That way you have a manageable subset of bitmaps in memory at any given time.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This article may be helpful. It describes both recursive traversal and an iterator based design.

But I've no idea how to implement it in the program.

You mean calling the function? Your first example should work, provided fun is defined and t is a pointer to bst_char. Another variation would be this:

char print(char item)
{
    putchar(item);
}

int main(void)
{
    bst_char tree;

    // Build the tree...

    bst_char_iterate(&tree, print);

    // Destroy the tree...

    return 0;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But why do some websites insist that my password HAS to have letters AND digits?

Mindless tradition, probably. For the longest time the bare minimum password policy was at least 8 characters including one upper case letter, one lower case letter, one number, and one special character.

These days a pass phrase is more secure due to its length, but many sites still have a character maximum and/or character combination checks that preclude a pass phrase. I can only assume it's because they follow "best practice" without putting any more thought into it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Because '!' and '}' have to be included in the try set. I'll put it a different way. Why is this loop?

for (int i = 0; i < 27; i++)
{
    for (int j = 0; j < 27; j++)
    {
        // Stuff
    }
}

Faster than this loop?

for (int i = 0; i < 127; i++)
{
    for (int j = 0; j < 127; j++)
    {
        // Stuff
    }
}

The same principle applies. The more you have to consider in what characters might be there, the longer it takes to actually identify them.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Put simply, the larger the character set used, the longer it takes to do a brute force crack of the password. If you just use letters, or even just lower case letters, your string would have to be longer to have the same security as if it used more varied characters.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How do the indexes relate in those two join tables? Can you show me an example of what the data might look like?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How exactly is your database structured?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I might organize my database so that I could do something like this:

var presentation = from m in db.PresentationModules
                   where m.PresentationId = pid
                   orderby m.ModuleIndex
                   select new
                   {
                       Module = m,
                       Components = from c in db.ModuleComponents
                                    where c.ModuleIndex = m.ModuleIndex
                                    orderby c.ComponentIndex
                   };

That way I could select a collection of modules and module components tied to the user. The collection can then be used in a more convenient manner than diddling around with indexes.

ddanbe commented: Indeed eternally awesome! +14
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I can think of several ways to do this, but more detail would help. What is this algorithm ultimately doing? Describing what you want to accomplish rather than how you want to accomplish it works better when looking for alternative methods.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I don't mind indeterminate values at all if I access an array with no initial value. I just don't want my program crashing because of some undefined behaviour that I don't understand.

Those two sentences are contradictory.

I don't understand traps by just looking at it either.

Imagine calling abort, but without the happy result for a user. ;) I wouldn't wish troubleshooting a trap representation on even the worst of my enemies.

I asked someone why it was undefined and they said to me that the OS only gives memory to a variable when it has a value otherwise nothing happens :S

Wow, that was a stupid answer. Whoever told you that is quite confused. You get memory, you just can't necessarily predict the contents of that memory.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why is accessing data in an uninitialised array undefined behaviour?

It really depends on where the array is defined. If it's a local array then it's undefined behavior just as accessing an uninitialized variable is undefined behavior. The contents of the array are indeterminate, which is the "official" reason for the undefined behavior.

The practical reason is that accessing random bits can trigger something like a trap representation and totally blow up your application simply by looking at a value.

Any ideas what I could do to keep the speed of uninitialising without breaking any rules?

I'd need more details on what you're using the array for. Restructuring the array so you only access it sequentially rather than randomly would be a good start, but that's not always appropriate for the problem.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is there a specific reason you used a struct for the weapon but a class for the adventurer?

If it were a class, Weapon would need getters and setters for each data member. At that point I didn't see any need, so just made them public by default as a structure. Adventurer on the other hand has other stuff going on (including stuff that I didn't include for brevity), so it makes more sense to lock down the data members.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The first chunk below lines up the decimals, but my "$"'s are too far, the second one fixes that and then the decimals are all F'd.

Right. The modifiers apply to the next item. If you don't want the "$" to be the next item, move it to before the modifiers:

cout << "$ " << fixed << setprecision(2) << setw(8) << right << 22.0 << endl;
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How are the weapons stored? Are they always a string in display format? Because it would be easier to have a weapon class that separates these things and makes it easier to work with:

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include <vector>

using namespace std;

struct Weapon {
    string _name;
    int _damage;
    int _value;

    Weapon()
        : _name(""), _damage(0), _value(-1)
    {}

    Weapon(const string& name, int damage, int value)
        : _name(name), _damage(damage), _value(value)
    {}
};

map<string, Weapon> supported_weapons = {
    {"Fist", Weapon("Fist", 1, -1)},
    {"Masamune", Weapon("Masamune", 52, 750)}
};

class Adventurer {
    vector<Weapon> _weapon_inventory;
    Weapon _equipped_weapon;
    int _base_damage;
public:
    Adventurer(int base_damage = 1)
        : _base_damage(base_damage)
    {
        _weapon_inventory.push_back(supported_weapons["Fist"]);
        equip("Fist");
    }

    void add_weapon(Weapon weapon)
    {
        _weapon_inventory.push_back(weapon);
    }

    Weapon equipped_weapon() const
    {
        return _equipped_weapon;
    }

    bool equip(const string& name)
    {
        auto match = find_if(
            _weapon_inventory.begin(), 
            _weapon_inventory.end(), 
            [&name](const Weapon& weapon) { return weapon._name == name; });

        if (match != _weapon_inventory.end()) {
            _equipped_weapon = *match;
            return true;
        }
        else {
            return false; // Weapon not available
        }
    }

    int roll_damage() const
    {
        return 1 + rand() % (_base_damage + _equipped_weapon._damage);
    }
};

In your code you might do something like this:

cout << "Choose a weapon to equip: ";

if (getline(cin, name) && equip(name)) {
    cout << name << " equipped\n";
}
else {
    cout << "Could not equip selected weapon\n";
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but my teacher said vectors allocate way too much memory and its bad to use so many of them in one program :(

Sounds like premature optimization to me. Vectors are quite efficient, they only hold just enough memory to contain and manage what you put in them. If you choose what you put in carefully, it takes effort to waste memory.

if i make the variable static, will i have to change anything else for it to work?

Not really. But you'll find that if you change the vector in one object, all others will change as well. That can be surprising and undesirable in a case like this, depending on your needs for this particular inventory.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but my task was to do by using strtok() fn

I love it when bad teachers ask you to do something with an approach that's woefully unsuited to it. :rolleyes: strtok isn't designed to "find" things, and any solution that attempts to use it that way is stupid.

You encountered one such reason for that. strtok doesn't recognize adjacent delimiters as being unique. There's no way around this without eschewing strtok and using some other ad hoc or non-standard tokenization library.

If I haven't been clear, strtok is the wrong solution. You cannot solve this problem just with strtok, period.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

From what I understand set() creates a column that will hold something less than it's size, and << right or << left will justifiy it.

Correct. But note that with the modifiers, typically they only affect the next item in the chain, not all further items.