deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The difference between using refrences(&var), and pointers(*var) is that using refrences is more efficent because you do not have to derefernce the object.

While there's potential for such an optimization, I wouldn't rely on it. The benefit of references is largely syntactic convenience (for more than you probably expect).

Am I right, and if I am why use pointers then?

Pointers can point to nothing, references cannot. This may seem like a minor thing, but it's actually pretty big. Pointers can also be reassigned to point to another address while references are stuck. Changing the "thing" being aliased is pretty critical when using pointers for things such as linked data structures. And of course, dynamic memory specifically works with pointers, so at the very least you'd need to remove and add indirection to work with it as references (not recommended).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

When you say *p++, what really happens is *(p++). So you're evaluating to the value pointed to by p, and then incrementing the address stored in p. So let's break it down:

y = &x;

The address stored in y is 500 (going off your original stated assumption for simplicity).

z = y;

The address stored in z is 500. Now y and z both point to x.

*y++ = *z++;

The value stored in the object pointed to by z is copied into the object pointed to by y. After this happens, both y and z are incremented by 4 bytes (ie. the assumed size of an int). Note that the assignment is directly equiavelent to x = x, because both y and z point to the same address.

x++;

The value stored by x is incremented to 31.

printf("%d %d %d",x,y,z);

The output will be 31, 504, 504. All variables involved were incremented one time. For x that means the value 30 becomes 31, and for the two pointers, the increment skips the address value ahead by the number of bytes in the pointed to type. Since int is assumed to be 4 for this example, 500 becomes 504.

Ancient Dragon commented: excellent :) +14
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That's by design. Unverified and newbie members aren't allowed to create new tags, only use existing ones. You probably crossed the threshold between a newbie member and a community member (these are our terms for the permissions levels) in those three hours.

By the way, the criteria for promotion from newbie member to community member is 5 or more posts + 5 or more days of membership or 15+ reputation points. Judging by your stats, I'm going to guess that it was the post threshold that you hadn't crossed yet.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you have any ideas for a code snippet you'd like to see, please post them here. We can't depend on the snippet writers to come up with all of the ideas, can we? ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hello Qonquest, unfortunately you no longer have the legal right to use the code you have written. By posting your code, you have granted DaniWeb an exclusive copyright license to your code according to DaniWeb's terms of service. You may no longer use it and have no rights to you code. Please delete your code from your computer.

If you're trying to be funny, it's in very poor taste. If you disagree with the policy as it's written, please start a thread in the feedback forum to encourage changes rather than employing back stabbing techniques in places Dani isn't likely to see.

happygeek commented: well said +11
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I found this unique program which will allow the user to create his own format specifier which will use "%b" as format specifier to convert a integer directly into binary.

Hardly unique, it's just another naive implementation of printf() that adds specifiers at the author's whim. Not that it isn't useful for learning how variable length argument lists are implemented, of course.

I want to know more about this code.

What do you want to know? I've implemented printf() for real (as in fully conforming to the C standard), so I can probably answer any questions you have about how it works under the hood.

However, I'm disinclined to give you a lecture about how the code works and why, so I'll kindly request that you ask some specific questions for me to answer.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

name_.first(firstName), name_.second(lastName)

C++ doesn't support initializing individual members of a member object in the initializer list. Ideally you'd want to add a constructor to the Name class that takes a first and last name, then write the initalizer list like this:

explicit Student(const std::string& id, const std::string& firstName, const std::string& lastName)
    : id_(id), name_(firstName, lastName){

    if(!isValidId(id) || !isValidName(name_)){
        throw "Student::Student(const string&, const string&, const string&): invalid input.";
    }
}

Otherwise, as Ancient Dragon mentioned, you'll need to eschew the initializer list and do a straight assignment in the constructor body:

explicit Student(const std::string& id, const std::string& firstName, const std::string& lastName)
    : id_(id){

    name_.first = firstName;
    name_.second = lastName;

    if(!isValidId(id) || !isValidName(name_)){
        throw "Student::Student(const string&, const string&, const string&): invalid input.";
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

u showed the use of fflush(stdout). a bit confusion here, coz i read in this page that using fflush is a bad thing. although they only mentioned it for the case of fflush(stdin).

Kudos for critical thinking and an eye for detail. :) The difference between good and bad with fflush() is indeed in the argument. fflush() is defined only for output streams or update streams presently in an output orientation. It's not designed for input streams, and technically, passing an input stream or update stream in input orientation to fflush() invokes undefined behavior.

So fflush(stdout) is fine and dandy while fflush(stdin) is undefined behavior.

Note that the two are totally different in expectations as well. When someone uses fflush(stdin), they typically expect the functionality to be akin to this:

if (the stream contains characters)
{
    /* Extract and discard excess characters */
    int ch;

    while ((ch = getc(stdin)) != '\n' && ch != EOF)
        ;
}

The "if the stream contains characters" part is not possible without delving into non-portable options. But the concept of "flushing" an input stream is usually reading and throwing away characters until the stream is empty.

fflush(stdout) on the other hand is all about writing unwritten characters. If you send a prompt to the screen, flushing stdout will force that prompt to be displayed immediately. If you're writing to a file, flushing the file stream will force any buffered characters to be written to the file. This is …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Make an array with every exercise and randomly pick one?

Yup. Though for a workout generator you probably don't want to pick the same exercise twice, so a random shuffle may be more appropriate.

How would I go about doing that?

Here's an example:

#include <stdio.h>
#include <stdlib.h>

#define length(x) sizeof (x) / sizeof *(x)

static const char* data[] =
{
    "test 1",
    "test 2",
    "test 3",
    "test 4",
    "test 5"
};

int main(void)
{
    int indices[length(data)];
    int i;

    /* Initialize the indices */
    for (i = 0; i < length(data); ++i)
    {
        indices[i] = i;
    }

    /* Randomly shuffle the indices */
    for (i = 0; i < length(data) - 1; ++i)
    {
        int r = i + (rand() % length(data) + 1);
        int temp = indices[i];
        indices[i] = indices[r];
        indices[r] = temp;
    }

    /* Select a portion of the shuffled array */
    for (i = 0; i < length(data); ++i)
    {
        printf("%s\n", data[indices[i]]);
    }

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

The #define directive is a glorified cut and paste. You can see why that macro is wrong by doing the cut and paste manually:

if(a=='A','B','C','D','E','F','0','1','2','3','4','5','6','7','8','9')
    printf("hexadecimal");

Well, you may not see it because this is a common confusion point for beginners to C. You don't compare a variable to a list directly like this, you must compare the variable to each individual item. So to compare against 'A', 'B', 'C', 'D' (because it's shorter for this example), you'd do this:

if (a == 'A' || a == 'B' || a == 'C' || a == 'D')
    printf("A, B, C, or D\n");

Obviously that's tedious, so a better solution is to store the "list" of matches in an array and then loop over the array while doing that comparison:

#include<stdio.h>

int main(void)
{
    char const hex[] = "0123456789ABCDEF";
    char ch;

    printf("Enter a character: ");
    fflush(stdout);

    if (scanf("%c", &ch) == 1)
    {
        int i;

        for (i = 0; hex[i] != '\0'; ++i)
        {
            if (ch == hex[i])
            {
                printf("Hexadecimal\n");
                break;
            }
        }
    }

    return 0;   
}

The take-away lesson is that C doesn't do jack for you and there's very little "magic". You have to do everything explicitly, or use a library to do it for you explicitly.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I only glanced over your post, but I'm 99.9% sure that it's the classic stream garbage problem when mixing formatted and unformatted input.

You see scanf() is special in that most of the time it will discard leading whitespace from the stream and leave trailing whitespace. gets() on the other hand, doesn't discard leading whitespace and will stop reading when it encounters a newline. So what happens when you use scanf() followed by gets() when scanf() leaves a newline in the stream?

You guessed it: it appears that gets() is skipped because it terminates successfully on the first character, the newline. The following program exhibits the problem clearly:

#include <stdio.h>

int main(void)
{
    char s[BUFSIZ];
    int d;

    printf("Enter a number: ");
    fflush(stdout);

    while (scanf("%d", &d) == 1)
    {
        printf("You entered %d. Enter your name: ", d);
        fflush(stdout);

        if (fgets(s, sizeof s, stdin))
        {
            printf("You entered '%s'\n", s);
        }

        printf("Enter a number: ");
        fflush(stdout);
    }

    return 0;
}

There are two common fixes:

  1. Don't use scanf(). Always use some variant of fgets() to read lines from the stream and then parse them using sscanf(). This way the stream is always kept pristine for fgets().

    #include <stdio.h>
    
    int main(void)
    {
        char s[BUFSIZ];
        int d;
    
        printf("Enter a number: ");
        fflush(stdout);
    
        /* Note that s is being reused here as the temporary line for d */
        while (fgets(s, sizeof s, stdin) && sscanf(s, "%d", &d) == 1)
        {
            printf("You entered %d. Enter your name: ", d);
            fflush(stdout);
    
            if (fgets(s, sizeof s, …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Will you please tell how many and which one statements are wrong in the code I have given ?

  • The code doesn't include <stdio.h>, which is technically OK except in the case of functions with variable length argument lists like printf(), where the behavior is undefined. Either way, best practice is to include the headers you need.

  • <string.h> isn't included either.

  • char name[]; is illegal because the array doesn't have a size. If it happens to compile, it's because of a compiler extension. In C99 the "struct hack" has been blessed as flexible array members. However, the member must be the last one in the structure, and the feature is questionable in writing robust code. Further, if I recall correctly that feature doesn't apply to unions.

  • const union emp e1; is exceptionally stupid, in my opinion. Of course there's the obvious problem of not initializing the union, but there's also the conceptual issue of a const union being nonsensical in the first place.

  • strcpy(e1.name,"H"); won't work because e1 is const, obviously.

  • e1.age=45; won't work because e1 is const, also obviously.

  • printf("%f\n",e1.salary); is unspecified behavior because you're requesting the value of a different member than the one previously stored (.age, in this case). Will it work? Probably, but it's not strictly required to do what you expect, and you'll need to consult your compiler's documentation to find out exactly what does happen.

    I can't confidently say that it's undefined behavior without consulting the C standard (though I'm reasonably sure), …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I already learnt linked list, trees and all.

Clearly you haven't realized how many variations of the above there are. Do you know intimately all of the tree variations listed here? That's just a teeny tiny helping of tree variations and enough to take up a few months of your learning time. You can find a rather huge list of algorithms and data structures that is fairly regularly updated here.

If you do it thoroughly, you could spend years learning about nothing more than tree data structures. So I'm skeptical when anyone says they're "done" learning something so deep and broad as a category of data structures.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If I write a C++ program and compile it into an executable file AND, don't have to install the program, will I have trouble running that C++ written program on other platforms?

Yes, you probably will. The executable itself is specific to the operating system and chipset where you built it. For example, if you try to run a Windows executable on Linux without an emulation layer like Wine, it'll fail.

Portability at the code level is about compilation, not execution. If your code is 100% portable, you should be able to rebuild it on any platform with a compiler and not encounter errors. There are also degrees of portability; it's difficult to write a completely portable program, but you can make porting the code easier by segregating the non-portable parts.

At a higher level you have things like byte code portability (a la Java) where the code is compiled into an intermediate byte code that's subsequently run by a virtual machine. The compiled byte code can be executed on any platform that supports the virtual machine, and the end result is close to full executable portability.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

so this tells me that it doesn't refer to first element of array or I should say that it is not giving us address of first element of array , rather giving us address of an array of a particular size ? am i right ?

This is where people often get confused. The address of the array is the same as the address of the first element. The difference between a pointer to an array and a pointer to the first element is how that address is interpreted through the data type.

Later down the road you can use this concept to your advantage through a technique called type punning.

So this means these statement will give wrong result

It's not that it won't work as expect, but that's a possibility. Passing a type that's unexpected to scanf() or printf() will invoke undefined behavior. At that point, anything at all could happen, which includes working as expected.

My biggest issue in the past with correcting this error has been the "it works for me" logical fallacy. I'll say that the code is buggy, and the author will respond with "but it works for me".

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

means code written above will not work ? because sizeof will not work as you have said ?

It will work, but only because the function parameter is a pointer to an array.

here p is a pointer to an array. so sizeof(*p) is size of complete array ? is this right ?

Yes, that's it exactly.

Will you please tell that when we say &a, then isn't it refer to first element of array ? it is a question in one book. i am not getting it.

This is where people tend to get confuzzled. The address is the same, but the type is different. So for int a[5];, a gives you a pointer to int and &a[0] also gives you a pointer to int, because both of these are value context expressions on the array. &a is an object context expression on the array, so the result, even though you get exactly the same address, has a different type: int(*)[5].

Note that this is why the following call to scanf() is buggy:

char name[50];
scanf("%49s", &name); /* The ampersand shouldn't be there! */

The reason why it's buggy is because scanf() is being passed a pointer to an unexpected type. scanf() expects char*, but what's actually passed is char(*)[50].

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

one last point i wana ask which is generated from this explanitaion only.
will you please this line again ? "As an operation to the address-of (&) operator. When you say &a, you get a pointer to an array, not a pointer to a pointer to the first element. If this expression were evaluated in value context, it would be impossible to create a pointer to an array, which would be problematic as that's the type of nested dimensions in a multidimensional array."

I suspect you haven't yet encountered pointers to arrays in their explicit form:

#include <stdio.h>

void foo(int (*p)[5])
{
    /* 
        Note that sizeof won't work here without a pointer to an array
        because we need the size of the whole array object, not just a pointer.
    */
    for (int i = 0; i < sizeof *p / sizeof **p; i++)
    {
        printf("%d ", (*p)[i]);
    }

    putchar('\n');
}

int main(void)
{
    int a[] = {1, 2, 3, 4, 5};
    int (*pa)[5] = &a;

    foo(pa);

    return 0;
}

You can also probably guess why they're not often used: the syntax for declaring and dereferencing a pointer to an array is...awkward.

But I think the part of my explanation that was troubling is mention of pointers to arrays as nested dimensions in a multidimensional array. That was wrong, and I have no excuse. What I intended to write (how it came out the way it did is beyond me) is that a pointer to an …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In this article we try to abuse the preprocessor so much that C++ no longer looks like C++.

#include <iostream>

#define also ,
#define stop ;
#define begin {
#define end }
#define args(x) (x)
#define scalar int
#define letter char
#define ref(x) x*
#define seq(x, n) x[n]
#define start main
#define print std::cout <<
#define nl << std::endl
#define from(x) = x;
#define to(x) i < x; i++)
#define repeat_with(x) for (int x
#define index(a, i) a[i]

scalar start args(scalar count also ref(letter) seq(args,))
begin
    repeat_with(i) from(0) to(count)
    begin
        print index(args, i) nl stop
    end
end
NathanOliver commented: My boss would kill me if he saw this +9
major_tom3 commented: The finest bit of satire I have seen on a C++ thread. Made my day! +0
Satyrn commented: ahh crafty. I love this idea but I would hate reviewing code that did this ><. This isn't Python! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@deceptikon will you please write it in again into more simpler form ?

It really depends on what you want the code to do, but if you're trying to display the contents of the 2D array with pointer notation, you don't even need an intermediate pointer variable:

#include <stdio.h>

int main(void)
{
    /* This is better because it highlights the structure of the array more clearly */
    int a[][2] =
    {
        {1, 2},
        {3, 4}
    };
    int i, j;

    /* At the very least, use braces around the outer loops */
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 2; j++)
        {
            /* Note how the pointer notation still works with an array variable. */
            printf("%d ", *(*(a + i) + j));
        }
    }

    /* This makes output cleaner for the next program */
    putchar('\n');

    return 0;
}

@sepp2k will you please tell me what "decays" means ? I have read it at more than 20 places. but I never get it's meaning. if any body asks me a[] is an array or pointer or both ? then what should i say to him/her ? please elaborate!

"Decays" is used because pointers are seen as lower level entities from arrays. What really happens is an array variable name, when used in value context, will be converted to a pointer to the first element of the array. Thus the following two printf() calls are functionally identical:

int …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

And i want to ask that in p[] definition, why it is written (int) with every element since a is already an pointer.

It's already a pointer, but the type is different. Try removing the cast and you'll get an error similar to: "type mismatch between int(*)[2] and int*"

The fact that the cast hides an error should give you pause when writing code like this, because it suggests that you're doing something stupid. In particular, it's not safe to assume that you can pun a 2D array into a 1D array using a pointer because there's potential padding at the end of each 1D array in a 2D array that could produce trap representations.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

size_t //Eerm, what is size_t?

It's a typedef for an undisclosed unsigned integer type (usually int or long). It's defined in <cstddef> along with a number of other C-inherited headers, and the intended usage is as the result type of the sizeof operator.

Since sizeof is often used to calculate the number of elements in an array, it also makes sense to use size_t as the index variable type.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I came across this program in the C++ section. How to do something similar in C?

While that program is indeed written in C++, the conversion to C is trivial as the overall structure doesn't depend on anything specific to C++. The library being used is Windows' Win32 API.

I see only a few minor things that need to be changed (there may be multiple instances of each):

  1. Variable declarations mixed with statements may not be legal in your version of C. Declare all variables at the start of a block.

  2. The bool type may not be available in your version of C (if it is, include <stdbool.h>). You can replace it with int, and true/false with 1 and 0.

  3. Replace <iostream> with <stdio.h>.

  4. Remove using namespace std;

  5. Either remove cin.ignore(); or replace it with getchar();.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Strings are not arrays so they dont end in \0 right? So how would i check if there is anything in the string at all?

There are a number of options, but if you want to say what you mean then this one stands out:

string s;

if (getline(cin, s))
{
    // Check for emptiness
    if (s.empty())
    {
        cout << "Empty!" << endl;
    }
    else
    {
        cout << "You typed '" << s << "'" << endl;
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You can't use the == operator to compare arrays. Well, you can, but it almost certainly doesn't do what you expect or want.

Ideally you'd use a std::string object instead of an array of char for strings, because then the == operator is overloaded and does what you want. Otherwise, you're stuck with the C-style method of calling strcmp():

#include <cstring> // Include this guy for strcmp()

...

if(strcmp(_cFileName, "HELP") == 0)
{
    // The user typed "HELP"
}

Now the user typing nothing is a bit harder because nothing will be written to the string. You must initialize the array to an empty string, and then you can compare the first character against the string termination character to see if nothing was written:

_cFileName[0] = '\0'; // Clear the string

...

if (_cFileName[0] == '\0')
{
    // The user typed nothing
}

On a side note, the system() function is declared in <cstdlib>, which you neglected to include. This is an error that your compiler probably overlooked, but you shouldn't rely on that behavior.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hi deceptikon, what is the content of input file (in your case test.txt). It is nowhere mentioned.

I used a super duper secret and obscure test case for the content of the file:

1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24

;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It compiles and runs up until the first function is called then crashes

I'm surprised it compiles. What compiler are you using? Anyway, there are a number of problems with your code such that it would be faster to give you a good example instead of enumerate the existing issues.

So here is a program that reads numbers into a 2D array, multiplies them by a user provided multiplier, and saves the result to a file with optional echo to the standard output. Please ask questions as I'm sure you'll have at least one. Note that I've taken care to comment interesting or important things in anticipation of questions you might not be in a position yet to ask:

#include <stdio.h>
#include <stdlib.h> /* For EXIT_SUCCESS and EXIT_FAILURE */

#define ROWS 4
#define COLS 6

int FileLoad(FILE* in, double a[ROWS][COLS], int stdout_echo);
void FileSave(FILE* out, double a[ROWS][COLS], int stdout_echo);
void Multiply(double a[ROWS][COLS], double multiplier);
void FlushLine(FILE* in);

int main(void)
{
    FILE* fp = fopen("test.txt", "r+");
    double a[ROWS][COLS];
    double multiplier;
    int rc;

    /* Always check to see if the file opened successfully */
    if (!fp)
    {
        /* perror() also prints a useful system error for troubleshooting */
        perror("Error opening file");
        return EXIT_FAILURE;
    }

    if (!FileLoad(fp, a, 1))
    {
        fclose(fp); /* Don't forget to close the file! */
        return EXIT_FAILURE;
    }

    /* 
        Reset both the error state and file position. 
        This way we can safely switch to write mode.
    */
    clearerr(fp);
    rewind(fp);

    printf("Please enter a multiplier: ");
    fflush(stdout); /* …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The original meaning of hacker back in the 1990's was basically a n00b of programming, maliciously or not.

The original meaning of hacker dates back to the 1960s and was the opposite of a n00b.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Test Foo{1, 2, 3} but not Test Foo = {1, 2, 3}

Those are not the same thing. The first is actually an alternative to the explicit Test Foo(1, 2, 3) while the second is an implicit expression similar to Test Foo = 123 (assuming you supported Test(int) as a non-explicit constructor).

And once again assuming that Test(int) is supported, you probably already know that Test Foo(123) is not the same as Test Foo = 123. The equals sign makes all the difference in your example.

Adding the curly brace alternative to C++ was a mistake, in my opinion.

triumphost commented: Ahh Thank you. Just needed that. +5
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Most likely 1,048,576 items the size of Cand is too much memory for malloc() to find and allocate in a single contiguous block. You might be able to call perror() for a more useful error message, but I'm willing to bet even if you do get a message, it'll be along the lines of what I just said.

Try allocating fewer items.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
Perry31 commented: Thanx Deceptikon... +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I see three potential alternatives:

  1. Keep the live preview, but let us toggle it with a check box (and remember the choice).
  2. Keep the live preview, but let us toggle it with a profile option.
  3. Ditch the live preview in favor of a preview request (perhaps in an AJAX popup).

I'm actually in favor of #3. After using it, the live preview is nifty but confusing. I find myself constantly clicking on the preview to set the cursor for editing...

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It has just come to my attention that he has indeed used this for spam. He is also using it for profit too.

Would this not be considered a breach of forum rules?

It's soundly in the gray area as far as self-promotion goes, but I think I'll allow it this time since we can't be expected to police the content of YouTube videos. If it were a link to his personal site (or if he starts promoting it directly in other threads) then I'd definitely call it a violation.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Or is this about a totally different thing?

Yes, totally different. You're thinking of fatal errors that halt execution without any chance for recovery. The return value from main() is for a graceful exit. Let's say you try to allocate memory and it fails. That's an error that can be caught and potentially recovered from, but if it can't be recovered from, exiting with an error status is reasonable:

#include <iostream>
#include <new>      // For bad_alloc
#include <cstdlib>  // For EXIT_FAILURE

using namespace std;

int main()
{
    try
    {
        int* mem = new int[12345];

        ...

        delete[] mem;
    }
    catch (bad_alloc const& ex)
    {
        cerr << "Error allocating memory: '" << ex.what() << "'\n";
        return EXIT_FAILURE;
    }
}
silvercats commented: that explains .....well .nice example +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

(1) means that there was something wrong.

While 1 can be an error code, the whole point of using 0 to signify success is because there's only a single success value but a large number of potential error values: anything in the range of int that's not zero.

So a more accurate description is that 0 is a success code sent to the C++ runtime while non-zero is an implementation-defined error code. The only portable values are 0, EXIT_SUCCESS (which is basically defined as 0), and EXIT_FAILURE. EXIT_SUCCESS and EXIT_FAILURE are both defined in <cstdlib>.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What is this new system we're talking about?

It's uniquely Daniweb's. Dani and I wrote it from scratch over the course of last winter.

Absolutely LOVE the new Daniweb...

Thanks! It's nice to get feedback, but positive feedback is better for the ego. ;)

ndeniche commented: Here's for your work +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What if I want to go from char* to BYTE*? I'd use reinterpret_cast right?

Correct, assuming BYTE isn't defined as char.

From const char* to BYTE* I'd do: reinterpret_cast<BYTE*>(const_cast<char*>(InitialValue.c_str()))

That's terrifying. First, casting away the const for the result of c_str() is begging for trouble, especially if you or some function you call tries to modify it. Second, the lifetime of the string returned by c_str() is questionable. You'd be much better off making a copy first, if the result is to have any significant life span.

But static_cast doesn't do this sorta thing and neither does dynamic so I'm not sure whether to reinterpret_cast or use c-style casting.

You can think of C-style casts as a god mode cast, they're essentially unrestricted. The C++ casts are restricted to their specific uses. const_cast is an ideal example: it modifies const/volatile qualifiers and nothing else.

If you're using C++ casts, then the best approach would probably be to avoid C-style casts entirely.

//See this cast? reinterpret_cast<char*>(&lpMsgBuf)
//Why do I have to use reinterpret to cast from a pointer?

The documentation for FormatMessage() says that you need to cast to LPTSTR, not char*. This distinction is important because LPTSTR could be defined as char* or wchar_t* depending on your unicode settings.

In this case, the Windows API is evil. Based on the flags from the first argument, FormatMessage() will treat the fifth argument differently. In one case it's a simple caller provided buffer …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

When a's destructor is not virtual and either b's or c's IS virtual, the program crashes. I'm not sure why this one happens.

I don't know off the top of my head, but I'd guesstimate that this invokes undefined behavior somehow and crashing was the result.

When a's destructor virtual and b's and c's destructors are not virtual, all three destructors are called. This one is really puzzling me.

Virtualness is inherited whether you specify it or not. Because a's destructor is virtual, b and c inherited that trait and are also virtual.

Finally, is there ever a time when you would not want to define all three destructors as virtual?

If none of the classes are used polymorphically, there's no need for virtual behavior. But I'd probably question a deep inheritance hierarchy that doesn't use abstract classes as the bases.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

"Help me please" is not a good question. Please be specific about what you want help with. I'd also recommend reading this tutorial on how to ask a smart question.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

My theory is that those libaries are needed for those 'built-in' functions and that those libaries do not exist on my system.

Yup. Your only two options are to find libraries that implement the functions being called, or simulate the functionality by writing definitions for those functions manually.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Sounds good to me.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So, I understand your code. But, how would I implement the member functions?
By how, I mean do I create my own implementation or use the implementation provided in the adaptee class?

You say you understand my code, but your question suggests otherwise. Clearly the member functions are implemented by calling relevant functions from the adaptee. Usually this is just a simple call as in my code. Sometimes it's multiple calls, but you're not rewriting anything that the adaptee already does.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

An adapter is really nothing more than a wrapper around another class that exposes a specialized interface. So at its simplest, a stack might be implemented like so:

template <typename T>
class Stack
{
public:
    bool empty() const { return _data.empty(); }

    void push(T const& x) { _data.push_back(x); }
    void pop() { _data.pop_back(); }

    T const& top() const { _data.back(); }
    T& top() { _data.back(); }
private:
    list<T> _data;
};
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Ahh I fixed the run-time error but the compile time still happens

Whoops. I forgot to mention that I also changed the specialization from char* to const char* to fix the compile time error. My bad.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
bool Contains(const char* LiteralType, bool CaseSensitive = true);

This declaration doesn't need to exist at all. const char* is already handled in your specialization of the overload for T. So remove that entirely and the compile time error will go away. However, you'll still have a runtime error from this:

std::vector<std::string> TempData;
for (size_t I = 0; I < TypeData.size(); I++)
    TempData[I] = TypeData[I];

Notice how the vector is never properly resized, yet you still try to access an index. Replace that with a call to push_back() and you'll be golden.

triumphost commented: Thank you! Much Appreciated. +5
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I can't reproduce the error because too many things are missing. Can you boil it down into a small and complete program that's compilable as-is? Also, what compiler are you using?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

sscanf(puppy,"%[^|]%f", &p, &num);

Try this instead:

sscanf(puppy,"%[^|]|%f", p, &num);

You forgot to extract the pipe character. Not to mention that the address-of operator is unneeded on p because it's already a pointer to char.

hanananah commented: Thank you! +0
Sokurenko commented: nice one, always happy to learn from u +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm curious, will I always have to type in an answer to a questions just to post or is this a noob action that I must do until I hit a certain number of posts?

It's an anti-spam measure. It'll go away quickly as the requirements are very lax: 15+ reputation points or 5 posts + 5 days since joining.

Stuugie commented: Thanks for the info! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

First, why does this not cause a stack overflow?

I'd wager that the empty function call was optimized away. You might be able to turn off all optimization switches in your compiler and get it to overflow.

Two, What is the difference between the two below?

The first is direct recursion and the second is indirect recursion. Direct recursion is when a function calls itself, and indirect recursion is where a function is called recursively by a different function that it calls. They're still both recursion, and can still both overflow the stack if not capped by a base case.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You pretty much nailed it for a simple class. It gets quite a bit more complex when construction, destruction, inheritance, polymorphism, and especially multiple inheritance enter the picture.

A good book covering the topic is this one.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You'll want to convert both a and b to strings, concatenate them, then convert the result back to an integer. Here's an example using string streams:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    int a = 4;
    int b = 5;
    ostringstream oss;

    oss << a << b;

    istringstream iss(oss.str());
    int c;

    iss >> c;
    cout << c << endl;
}