Tom Gunn 1,164 Practically a Master Poster

you need memset() to set a default value.

memset() is not needed. You can do it without calling a function by using an initializer for the array:

int array[4][2] = {0}; /* init all elements to 0 */
Hiroshe commented: thanks +2
Tom Gunn 1,164 Practically a Master Poster

There is no point in understanding the output. It's undefined behavior. The output could be different the next time you run the program. UB also makes the rest of the program undefined so you have to understand all of that craziness too. It's a waste of resources to understand UB, just don't invoke it with stuff like this. ;)

jephthah commented: yep. +12
Tom Gunn 1,164 Practically a Master Poster

You'll probably have to explicitly turn on the C99 mode.

Visual Studio does not have a C99 mode.

http://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards

Tom Gunn 1,164 Practically a Master Poster

Is it set to start automatically or manually?

Tom Gunn 1,164 Practically a Master Poster

This is the essence of what you're doing:

#include <iostream>

using namespace std;

int main()
{
    int *p[10];
    int val = 5;

    for (int x = 0; x < 10; ++x) p[x] = &val;
    for (int x = 0; x < 10; ++x) cout << *p[x] << '\n';
    val = 10;
    for (int x = 0; x < 10; ++x) cout << *p[x] << '\n';
}

The pointers in the vector all point to the same array because the pointer is copied into the vector and not the array itself. A way to fix the problem is to have a vector of vectors and then create a new vector from the array when you want to push_back.

Tom Gunn 1,164 Practically a Master Poster

Did I do it right? the function doesnt seem to be returning anything

The function doesn't return anything because the return statement is commented away. The function returns a junk pointer. I don't think strtok is the best way to do this because you don't have a good way of knowing when there's no more string left without counting the delimiters somewhere in instring.

Tom Gunn 1,164 Practically a Master Poster

So you can do things like a = b++ and a = ++b . Chaining and combining expressions accounts for most of the weirdness in how operator overloading works. But you don't have to follow the conventions even though it's a good idea to stick to idioms that everyone expects. Your operators could return void and still work for the basic cases of b++; and ++b; .

Tom Gunn 1,164 Practically a Master Poster

A binary operator is an operator like + or / that have two operands, one on each side. A unary operator is an operator that only has one operand:

a * b // binary
true && false // binary
-1 // unary
!x // unary
Tom Gunn 1,164 Practically a Master Poster

but my ans is always "password is wrong"

Print both strings and eyeball them:

cout << ">" << passFromFile << "<\n";
cout << ">" << passFromUser << "<\n";

There's probably whitespace or something that makes the difference.

Tom Gunn 1,164 Practically a Master Poster

The printf symbol for long long unsigned int is %llu.

In C99 it is. The I64 size is a Microsoft CRT extension, but the Microsoft CRT doesn't support C99, and %llu doesn't work.

http://msdn.microsoft.com/en-us/library/56e442dc(VS.71).aspx
http://msdn.microsoft.com/en-us/library/tcxf1dw6(VS.71).aspx

Wait, why do you need to malloc? Wouldent:

unsigned long long  int *x = 600851475143ULL;

Work the same way?

malloc allocates a number of bytes given by the argument and returns a pointer to heap memory of that size. The original code allocates 600851475143ULL * sizeof(unsigned long long) bytes. Your code points x to the address 600851475143ULL and probably won't work on a protected memory system and certainly not on a system without gobs of memory. Though the malloc approach has a similar problem where allocating that much memory is questionable.

Tom Gunn 1,164 Practically a Master Poster

I really don't think the instructor thought of all the things you mentioned in basic classes on overloading.

I guess I wasn't any help then. :(

Tom Gunn 1,164 Practically a Master Poster

What's wrong with what you have? I mean, you're not going to find anything a lot shorter.

Tom Gunn 1,164 Practically a Master Poster

He claimed you can just do n++ instead of n = n->next. I disagree.

With your List class that's true. But C++ allows you to overload operators to do different things. You can overload the ++ operator to do n = n->next. That's what the list<T>::iterator does:

#include <iostream>
#include <list>

using namespace std;

int main()
{
    list<int> values;

    for (int x = 0; x < 10; ++x) values.push_back(x);

    for (list<int>::iterator x = values.begin();
         x != values.end();
         ++x)
    {
        cout << *x << '\n';
    }
}

list<T>::iterator is a class that overloads the ++ operator and other things to match certain rules about how the iterator type should work. In a way list<T>::iterator corresponds to your Node class.

[edit]
This is a quick example to show what I mean. It uses a wrapper around Node to implement an iterator. It's not fancy or 100%, but it shows the concept a little better than the first example.

#include <iostream>
#include <cstddef>

using namespace std;

class Node {
public:
	int data;
	Node * next;
};

class Iterator {
    friend class List;
    Node *_node;
public:
    Iterator(Node *node=NULL): _node(node) {}
    int& operator*() { return _node->data; }
    Iterator& operator++()
    {
        _node = _node->next;
        return *this;
    }
    friend bool operator==(const Iterator& lhs, const Iterator& rhs)
    {
        return lhs._node == rhs._node;
    }

    friend bool operator!=(const Iterator& lhs, const Iterator& rhs)
    {
        return !(lhs._node == rhs._node);
    }
};

class List {
public:
	List();
	void append(int i);
	void print();
	void test();

private:
    Iterator front;
    Iterator …
Tom Gunn 1,164 Practically a Master Poster

There is not a loop anywhere in that function. It should loop over the nodes until NULL and stop early if a match is found:

int found = 0;

while (move != NULL)
{
    if (move->level == level && move->id == id)
    {
        found = 1;
        break;
    }

    move = move->next;
}

if (found) printf("\n\nStudent Record Is FOUND");
else printf ("\n\nStudent Record Is NOT FOUND");
Tom Gunn 1,164 Practically a Master Poster

Are you implying that you gave him bad rep only for giving someone bad rep?

I'm just implying that what goes around comes around.

BTW, Do you really think he's crying for getting 1 point bad rep?

His response implies that he cares enough to bait me into a flame war.

He only doesn't find it nice if you give him bad rep, without any real reason (like anyone does).

He just doesn't like with my opinion and decided to lash out at me. News flash, if you have extreme views, someone is going to disagree with you.

Tom Gunn 1,164 Practically a Master Poster

The only thing that comes to mind is in your malloc call the value is an unsigned long long, but malloc takes a value of type size_t. size_t is probably going to be unsigned long or unsigned int instead of unsigned long long, so your unsigned long long value gets truncated to fit size_t.

The only way to fix it I can think of is to break the big chunk down into an array of smaller chunks and call malloc multiple times. Or use a heap allocator that can handle unsigned long long sizes.

Tom Gunn 1,164 Practically a Master Poster

Next time, try to elaborate your point so that the other person can comment on it.

Well, now you know how it feels to get negative rep you don't agree with. No chance to defend, just BAM, hit and run.

Linux is really a good designed OS.

Linux is a good OS. I agree.

I don't really want to start a flame war, but this is the truth.

Right. If you didn't want to start a flame war, you wouldn't have made such an inflammatory post. Sorry, but I refuse to take the bait.

iamthwee commented: amen +21
Tom Gunn 1,164 Practically a Master Poster

How often are pointers to functions used?

As often as they're needed?

Should i implement them in my programs?

Function pointers work great for callbacks and generalized behavior at runtime. If you're doing something where they can be used and they're the best choice, you should use them. What you shouldn't do is look for places to use a random cool feature you just learned. That results in bad designs.

Tom Gunn 1,164 Practically a Master Poster

I don't think that kind of thing can be taught. You just have to read code to see how other programmers did it and try out things for yourself. The more you do it the better you'll get at it. There's no 'right' way to design OO programs. Nobody can agree on what OO even means, much less how it should be practically applied. ;)

Start small and build on what you learn. That's how I did it, but I'm still not good at OOP.

Tom Gunn 1,164 Practically a Master Poster

tux4life, I challenge you to write the same program with the same features and restrictions and show me how it's so much better than mirfan00's that he deserved all of that harassment. You're quick to mouth off, but can you back it up with your own perfection?

This program is real rubbish, old style headers, conio, half of the code is commented out, system("pause")

The only old style header is <string.h>, and even though it's officially deprecated, it's not going away any time soon because then compatibility with C would go out the window.

There's no way to replace typed characters with a star using standard code. To do that you have to use something that isn't portable, and conio is as good a choice as any for a toy program.

Only 3 lines out of over 40 are commented out. I didn't get good grades in grade school math classes, but I'm pretty sure 3 isn't even close to half of 40.

You forgot to say that <string> should be included because the code uses the standard C++ string class. And you forgot to say that '\r' is a portable replacement for 13. For all the complaining about old style headers, you forgot to say that the only code using them is commented out so both can be removed. I see you complaining about the same things over and over, and ignoring other things that are in the same league or worse. It kind of …

Tom Gunn 1,164 Practically a Master Poster

I have found out that goto is bad in C++? Why? I just got a book the other day (for my birthday ) and it says it is fine to use.

Happy birthday! :) goto is too easy to use the wrong way. I think K&R calls it "infinitely abusable". goto is like multiple inheritance. Most of the time you don't need it, but when you do it makes all the difference in the world.

You only need a bracket {} after an if-statement if there is more than one afterward procedures(';').

A good compromise is always using brackets unless you can fit the whole if statement onto one line:

// fits on one line
// no brackets
if (done) break;

// kind of long for one line
// use brackets
if (option == 1)
{
    copy(
        myVector.begin(), 
        myVector.end(), 
        ostream_iterator<string>(cout, "\n"));
}

// two statements in the body
// brackets required
if (error)
{
    PrintError(error);
    break;
}
Tom Gunn 1,164 Practically a Master Poster

Here is a quick test to see how the two expressions work:

#include <stdio.h>

int main()
{
    int a[] = {2, 1};
    int *p = a;

    printf("%d\n", (*p)++);
    printf("%d\n", *p);
    printf("%d\n", *p++);
    printf("%d\n", *p);

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

You are passing the address of n and c. That means nextprime should expect pointers:

int nextprime(int *n, int *c);

Then inside nextprime, n and c are already pointers so you need to dereference them to get to the value. n and c gives you the address, *n and *c gives you the value at that address.

You can almost fix things inside nextprime by changing the &'s to *'s, but because of precedence *n++ and other expressions like it won't do what you want. Instead of incrementing the value at the address pointed to by n, it increments the address of n and evaluates to the value at that new address.

To get the right precedence you need to use parentheses: (*n)++; . Dereference n, then increment that value. Everything you have in main is perfect, but a '\n' at the very end couldn't hurt. ;)

#include <stdio.h>
int nextprime(int *n, int *c);

int main() {
  int n = 0, c = 0;
  printf("%d, ", nextprime(&n, &c));
  printf("%d, ", nextprime(&n, &c));
  printf("%d, ", nextprime(&n, &c));
  printf("%d\n", nextprime(&n, &c));

  return 0;
}

int nextprime(int *n, int *c) {
/* This function will return the next prime number. Simple set n and c at 0 and 
   call the function whenever you need the next prime number. */
   if(*n == 0) {
      (*n)++;
      return 2;
   }
   if(*c == 0) {
      (*c)++;
      return (6*(*n))-1;
   }
   if(*c == 1) {
      (*n)++;
      (*c)--;
      return (6*(*n))+1;
   }
}
Tom Gunn 1,164 Practically a Master Poster

You can call the function and skip those first 15 bytes. That's easy:

RC4(&data_key,3,enc_data+15,clear_data);

I don't know if it will work though. It depends on how the encryption works.

Tom Gunn 1,164 Practically a Master Poster

When you say bytes 15-18, is that the plain text or the cipher text?

Tom Gunn 1,164 Practically a Master Poster

Good luck and thanks!

I think it would be better to show your code with the pointer stuff so that someone can help you understand where you went wrong than to show your code without the pointer stuff and hope somebody does all of your work for you.

Salem commented: Indeed +36
Tom Gunn 1,164 Practically a Master Poster

It works both ways in Windows.

Tom Gunn 1,164 Practically a Master Poster

You don't always have to store the actual value the way float and double do. If the problem allows it, you can write your own data type that uses exponent representation just like you showed in your post:

typedef struct 
{
    long base;
    long exponent;
} exponent_t;

Then do math on it like you learned in grade school. :)

kvprajapati commented: Good advice. +3
Tom Gunn 1,164 Practically a Master Poster

If you specify a value, it overrides the rule. If you don't specify a value, it defaults to one more than the previous constant. If you don't specify any value for the first constant, it starts at 0:

enum 
{ 
    A,    // A == 0
    B,    // B == 1
    C=10, // C == 10
    D=20, // D == 20
    E,    // E == 21
    F     // F == 22
};
Tom Gunn 1,164 Practically a Master Poster

This should help give you ideas for how it can be done without all of that extra work and buggy loops:

#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>

using namespace std;

namespace
{
    const double PI = 3.14159;
}

bool IsValidFixed(string s)
{
    int dots;

    // check that only digits and dots are present
    // check that only 1 or 0 dots are present
    return s.find_first_not_of(".0123456789") == string::npos &&
           ((dots = count(s.begin(), s.end(), '.')) == 0 || dots == 1);
}

string UpperCase(const string& s)
{
    string temp;

    for (string::size_type x = 0; x < s.length(); ++x)
    {
        temp += toupper(s[x]);
    }

    return temp;
}

int main()
{
    string number;

    while (getline(cin, number))
    {
        if (IsValidFixed(number)) cout << atof(number.c_str()) <<'\n';
        else if (UpperCase(number) == "PI") cout << PI << '\n';
        else cerr << "Not a valid number\n";
    }
}

It's important to see that the name of a macro isn't the same as the string you're parsing. You only need one PI. ;) The casing problem is with the input string, and that can be fixed by forcing all of the characters to a single case.

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

Calling main recursively isn't allowed in C++. It's a bad practice even if your compiler allows it. ;)

What were you trying to accomplish?

I think it's an input parsing algorithm that looks for fixed point values or variations of PI. The fixed point value is checked and if it's PI, the string is replaced with the value of PI. Something like this:

if (IsValidFixed(number)) continue;
else if (UpperCase(number) == "PI") number = PI;
else
{
    Panic("Not a valid number");
}
Tom Gunn 1,164 Practically a Master Poster

Your numbers are all chars. cout will print them as chars, not ints. But you can't print them as ints because some of them have to be 'X', right? So use an array of strings instead of chars:

#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>

using namespace std;

void PrintBoard(string Number[], int sz)
{
    cout << "-+-+-+-+-+-+-\n";

    for (int x = 0; x < sz; x += 4)
    {
        cout << Number[x] << '|' 
             << Number[x+1] << '|' 
             << Number[x+2] << '|' 
             << Number[x+3] << '\n';
        cout << "-+-+-+-+-+-+-" << endl;
    }
}

int main()
{
    string Number[16];
    srand(time(0));
    bool GameOver(false);
    bool GameOverWin(false);

    cout << "enter 16 numberss between 10-40" << endl;

    for (int x = 0; x < 16; ++x)
        cin >> Number[x];

    int k = 51;
    while(k) {
        do {
            PrintBoard(Number, 16);

            bool bValidMove;

            do  {
                int randNumber = rand() % 41 + 10;
                bValidMove = true;

                for (int x = 0; x < 16; ++x)
                {
                    if (Number[x] != "X" && randNumber == atoi(Number[x].c_str()))
                        Number[x] = "X";
                }
            }
            while(!bValidMove);

            // test for game over. no changes. i removed it to make the code shorter

            if(GameOver)
            {
                PrintBoard(Number, 16);
                cout << "BINGO!, you won congrat" << endl;
            }
            cin.get();
            cin.get();
        }while(!GameOver); 
        --k;
    }     
    cin.get();
    cin.get();
    return 0;
}
Tom Gunn 1,164 Practically a Master Poster

It helps to know what you expected. I'll guess that you wanted -25.0. Here's why you get -100.0. a=2*(s-u*t)/squ(t); uses the squ macro, and squ replaces itself with the macro text x*x with x replaced by the argument t. Your statement looks like this after the replacement:

a=2*(s-u*t)/t*t;

* and / have the same precedence and are evaluated left to right. If you wanted -25.0 as a result, x*x has to be surrounded by parentheses:

a=2*(s-u*t)/(t*t);

That's why it's a good habit to surround your macro text expressions with parentheses. And for the same reason, the macro parameter:

#define squ(x) ((x)*(x))

You should be very careful with macros like this because if you pass an expression with side effects as the argument, the side effect will be evaluated twice:

int b = 1;

printf("%d\n", squ(b++)); /* squ(b++) replaced with ((b++)*(b++)) */
printf(“result :%f”,a);

If you don't print a '\n' character somewhere, the output might look weird.

jephthah commented: nice explanation +11
tux4life commented: I agree with you :) +10
Tom Gunn 1,164 Practically a Master Poster

just one question, could you use any othe colors then blue, green, red?

You can combine red green and blue just like in art class. :) Put them together with a binary or:

#include <iostream>
#include <windows.h>

using namespace std;

HANDLE SetColor(
                HANDLE console, 
                int fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
                int bg = 0)
{
    if (console == NULL)
        console = GetStdHandle(STD_OUTPUT_HANDLE);

    SetConsoleTextAttribute(console, fg | bg);

    return console;
}

int main()
{
    HANDLE console = SetColor(NULL, FOREGROUND_RED, BACKGROUND_GREEN);

    cout << "Hello world!\n";
    SetColor(console, FOREGROUND_BLUE | FOREGROUND_GREEN);
    cout << "Teal.\n";
    SetColor(console, FOREGROUND_RED | FOREGROUND_BLUE);
    cout << "Purple.\n";
    SetColor(console);
}

You should read the link to SetConsoleTextAttribute. The character attributes page shows how to do all of this.

Tom Gunn 1,164 Practically a Master Poster

Expecting that this thread will be moved to the C# forum, I can answer it as a C# question.

EncryptMyData (byte[] plainData, out byte[] encryptionKey)<-- what the mean of this???

I'm guessing you mean the out parameter? It means that the caller passes in a reference of the same type and EncryptMyData has to set it to a new array before returning. Then the caller can use the new array. It's just like a ref parameter except out parameters don't have to be initialized by the caller before being passed.

Tom Gunn 1,164 Practically a Master Poster

Was the link I gave to Stack Overflow not good enough? You sure read it and absorbed the whole thing fast. It took me the better part of a slow work day to get it all.

Tom Gunn 1,164 Practically a Master Poster

A switch is easier until you have more than 1-9. Just try to write 0-999 with switches and you'll see how tedious and huge it gets. ;)

Tom Gunn 1,164 Practically a Master Poster
if (password == "pen15");

You have an extra semicolon at the end there.

[edit] You also need to include <string> because you use the string class and getline.

Tom Gunn 1,164 Practically a Master Poster

It's harder than it seems at first. 1-9 is easy, but 10-19 are different and need special cases. Then you need to do 20-99 and can reuse 1-9 inside, then 100-999 reusing everything with a prefix of n hundred. The higher the numbers you allow, the harder it gets to keep things short and simple.

I think switch statements are crazy for this problem. :) An array based approach is going to be much much shorter. You can store the string for each carefully selected part of a number, then break the number up and pick that string out of the array.

Stack Overflow had a cool discussion on the ways to do it.

Tom Gunn 1,164 Practically a Master Poster

Thanks guys I sorted it out

That's great! What did you do to fix it?

Tom Gunn 1,164 Practically a Master Poster

Do you want to wait till the very latest moment?

I want to be told by an authority that I'm breaking the rules, not some net nanny who just doesn't like that I'm actually helping instead of bashing people about code tags, "rusty code", and using compilers that are forced on them as if they had a choice.

You've to understand that we're just warning you.

No offense, but all I understand so far is that a bunch of people around here get off on putting others down and try to make themselves look important. I understand that there are people like that, and I have no intention of getting into a pissing match with the local good ol' boys. But I'm also not going to do what you say just because you say it. I've read the rules, and all of the links you keep giving me, and I think your interpretation is overly strict.

BTW, Is it that difficult to read a block of text?

It sure seems that way, because you missed this part in red:

Naturally giving away the answer is a subjective thing, so just make sure that the person you help can't just take your code and turn it in for a grade.

I say that he can't turn my code in for a grade because it uses two tricks with pointers that a student asking for help on this problem couldn't figure out independently.

Tom Gunn 1,164 Practically a Master Poster

Yes, but first: in C89 it's not called a designated initializer

I don't see how that's relevant. The rules I quoted apply to initializer lists with or without designated initializers.

and second: it doesn't get all those zeroes "by default", as already told by jephthah, they're automatically initialized to zero because you initialized the first element.

How is that different from saying that when you initialize one element in an initializer list, the rest default to 0? Same concept, different words.

Tom Gunn 1,164 Practically a Master Poster

You have a copy constructor, but it doesn't copy anything.

Tom Gunn 1,164 Practically a Master Poster

Seems like the new way is always longer if you want to initialize all the variables

Like most of the new features, there's a niche for them. The old ways are better for general use, I think.

>Structures, or any other variable, are not initialized to zero or any other value "by default"
Agreed, if we're talking about C89, but if you use designated initializers (C99) then the struct's data members (which weren't explicitly initialized) are automatically initialized to zero

It works the same way in C89. That's why int numbers[100] = {0}; sets all 100 numbers to 0 instead of just the first one and leaving the rest indeterminate.

Tom Gunn 1,164 Practically a Master Poster

I can't say what the problem is with what you've shown, but the list makes a copy of the object. Check your copy constructor for the Aircraft class.

Tom Gunn 1,164 Practically a Master Poster

I think a better way to go about it is to change your code to do it the Linux way. You shouldn't be using system anyway because it is bad for security.

Show which commands you're using from DOS and I can help you figure out how to do it in Linux without emulating DOS.

Tom Gunn 1,164 Practically a Master Poster

Wrong. Wrong. Wrong.

Structures, or any other variable, are not initialized to zero or any other value "by default" ... just because your compiler happens to do so, does not mean someone else's compiler does.

this error is probably the single-most source of broken code, and endless debugging efforts.

thanks for propagating crappy coding practice. :icon_rolleyes:


.

I'm sorry, but you are the one who is wrong. Since we're talking about a C99 feature, I'll quote the C99 standard concerning initializer lists:

If there are fewer initializers in a brace-enclosed list than there are elements or members
of an aggregate, or fewer characters in a string literal used to initialize an array of known
size than there are elements in the array, the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage duration.

If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate. If an object that has static storage duration is not initialized explicitly,
then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these
rules.

If there's no initializer list, you're right about local variables. …

Tom Gunn 1,164 Practically a Master Poster

A moderator hasn't told me that I've done anything wrong yet. Besides, the announcements are specific about homework without showing any effort. That's not the case here. The "Read this first!" even says that giving away answers is subjective.

If you want me to change how I post, you have to tell me exactly what I'm doing wrong and how you would do it the right way. Then convince me that your right way is better than my right way.

tux4life commented: Now I tell you that you've done something wrong! -2
Tom Gunn 1,164 Practically a Master Poster

That's more helpful, but a format specification would be better. Show an example of the input and output of the program and explain how the input got to the output.

Tom Gunn 1,164 Practically a Master Poster

what is the l for?

and i didn't understand this>> while (l==1)

It looks like another way to write a !done loop. These two are conceptually the same:

int l = 1;

while (l == 1)
{
    if (/*not more to do*/) l = 0;
    else
    {
        //do stuff
    }
}
bool done = false;

while (!done)
{
    if (/*not more to do*/) done = true;
    else
    {
        //do stuff
    }
}