deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Allow me to reformat your code in the way the compiler sees it. The problem should be easier to locate that way:

#include <stdio.h>
main(){
    int order;
    int price=5;
    int bill;
    int billd;
    int billf;
    scanf("Amount of Order: %d",& order);
    if (0<=order<=10)
        ;
    bill=(order*price);
    billd=(bill*0.1);
    billf=(bill-billd);
    {
        printf("Bill: %d",billf);
    }
    else if(11<=order<=20)
        ;
    bill=(order*price);
    billd=(bill*0.2);
    billf=(bill-billd);
    {
        printf("Bill: %d",billf);
    }
    else if(21<=order<=40)
        ;
    bill=(order*price);
    billd=(bill*0.3);
    billf=(bill-billd);
    {
        printf("Bill: %d",billf);
    }
    else
        ;
    bill=(order*price);
    billd=(bill*0.5);
    billf=(bill-billd);
    {
        printf("Bill: %d",billf);
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Code::Blocks uses MinGW by default, which is a port of GCC. That said, itoa should be available, if I recall correctly. Normally I'd ask what your switches are and to post some code which fails to find itoa, but a standard alternative is snprintf (or sprintf if you're not running C99 or later).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I suspect the confusion is the name p. You have two variables with the name p, which in this case is perfectly acceptable. However, it might be that you're seeing them as the same object, which is false. Consider this modification to fun:

void fun(int *meep){
    *meep = 15;
    meep = &q; 
    printf("%d ",*meep);
}

This definition is equally valid, and now it's more obvious that p and meep are completely independent objects that just happen to contain the same address as their value.

Now, with this modification, see if you can figure out why your result is 10 15. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How about you? Got any good replies like that?

The worst is when people assume that because the code compiles (ie. no fatal errors) then it's correct. Oddly enough, warnings often tell the real story about issues at runtime.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

First and foremost, you don't need to cast the return value of malloc. In fact, doing so can hide legitimate errors such as failing to include <stdlib.h>. Second, sizeof(char) is guaranteed to be 1 in all cases, so things like sizeof(char) * some_int are unnecessarily complex.

I have seen a few different ways of doing malloc error checking? Is one way better than the other?

As for checking the result, both x == NULL and !x will work; it's really a stylistic matter of which one you find more informative.

Are some exit codes better than others?

The only codes guaranteed to be portable are 0, EXIT_SUCCESS, and EXIT_FAILURE. But before you use 0 or EXIT_SUCCESS, keep in mind that both are treated as success codes. Why exit with 0, for example, if the program terminated unsuccessfully?

Is using fprintf with stderr better than using a printf statement?

Yes. printf is forced to stdout, but what if you want your errors to go to a log file rather than standard output along with non-error output? fprintf and similar give you more flexibility in error reporting.

Is using a return instead of an exit better?

Both are pretty awful in general, and it's because terminating on an allocation failure instead of trying to recover is usually not the most robust approach.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The comment tells you: "declared as an integer constant of type unsigned long int". The UL suffix explicitly tells the compiler that you want a value of type unsigned long.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This code was coverted from VB by simply replacing the 'And's and 'Or's.

One thing to note is that these are not comparable operators. And and Or are not short circuiting in VB, yet && and || are in Java. Whether this is relevant depends heavily on your logic, but it's a point that needs to be made. && and || are only directly equivalent to AndAlso and OrElse.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Technically the best case is the input tree is already AVL balanced, so the solution is legit from a complexity standpoint. The more practical problem with this solution is it adds a verification step regardless of the input tree and slows down the algorithm even when you need to adjust balance.

To properly determine if the solution is worth the cost, you'd need to measure how much of an impact the verification step has and compare against the probability of receiving a valid AVL tree as input. That leaves the realm of complexity theory, but it's something that must be done with actual code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This, malloc(sizeof *new); should be malloc(sizeof(Node)).

It can be, but doesn't need to be. That call to malloc is correct as it stands, and actually best practice. new is a pointer to Node. The operand to sizeof is the dereferenced new, which ends up being evaluated as Node rather than Node*. Because sizeof only evaluates the end type of the expression and not the expression itself, this dereference of an unintialized pointer is also quite safe.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Well, I was feeling under-qualified based on what I was seeing out there for available positions.

Job "requirements" lie like a rug more often than not, and the actual requirements tend to be significantly lower. But by demanding the world, it's easier to catch the better talent from the start.

Every time I read a listing that says you must have XYZ, I'm reminded of more than one position in 2000 that required 10 years of Java experience.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What am I missing here?

Two things:

  1. Student s(pName) is creating a variable called s via the const char* constructor of the Student class. I get the impression you're confusing this with a function declaration given your mention of a "variable name".

  2. You can generally add a const qualifier without issue, but it cannot be removed without a cast. This is what the book is explaining. pName does not have a const qualifier, but it can be safely passed to the Student constructor that expects a const qualifier. This qualifier will be added for you automagically and the parameter to the constructor will be treated as const.

The code isn't ideal, of course. pName should be declared as const to avoid subtle issues which could arise depending on how the constructor uses the pointer.

rubberman commented: Good explanation. +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Congratulations! You've found an inconsistency in terms with binary trees. :) There are actually a few of them, but counting levels is a notable one. As James said, each paper or book should be internally consistent, but you'll want to take care to follow the source material carefully. If you use multiple conflicting sources, pick one and convert the calculations of the others as necessary so that your stuff is internally consistent.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how would you do the math with the expression?

Push any operands. On an operator, pop the number of operands required, then push the result. Repeat until there's only a result. For example, 1 + (2 * 4 + 3) would be converted to 1 2 4 * 3 + +. It would be evaluated like so:

  • Push 1 - Stack: {1}
  • Push 2 - Stack: {2,1}
  • Push 4 - Stack: {4,2,1}
  • Pop 4 and 2, multiply them, and push 8 - Stack: {8,1}
  • Push 3 - Stack: {3,8,1}
  • Pop 3 and 8, add them, and push 11 - Stack: {11,1}
  • Pop 11 and 1, add them, and push 12 - Stack: {12}
  • You're done, pop the final result of 12 - Stack: {}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

"More vertically" is too vague. Can you provide a sample of what your teacher is asking for?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Will the malloc for ptr2 or ptr3 will allocate the same memory that has been freed by free(ptr1)..

Maybe, maybe not. It really depends on the memory manager malloc uses for that specific implementation. I wouldn't make that assumption though.

what will happen internally if I free a memory which is already freed.

Well, given that the block of memory no longer exists as far as the memory manager is concerned, bad things will happen. Officially, you invoke undefined behavior. In practice, you'll be looking at crashes, memory corruption, and potentially an unwanted release of a reused block.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You have a circular reference in your includes. The easiest fix as-is would be to remove the include for LinkedList.hpp in your LinkedNode.hpp header.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Not a strange question at all, and we got it quite often when the TOS explicitly claimed copyright to any posts made (it doesn't appear to do so any longer).

In the past, ownership of post content was in practice only to absolve us of responsibility for storing, editing, and deleting posts as necessary under the rules, and any IP for purposes of external copyright would still be happily relinquished by Dani and Daniweb LLC. But legally, you'd still need to request it.

Now it's not so clear, but without any claim of copyright, I'd lean toward default ownership of any IP going to the original author being how the law works. That's my interpretation, of course. I'll let Dani confirm or deny my assumptions. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how would i need to change this code to accept strings insted integers in avl tree?

Agreed with David W. Though the function seems entirely unnecessary. It's generally better practice to avoid having functions that do multiple things (ie. gather input and insert into a data structure) in favor of just one (ie. only gather input and return it or only insert into a data structure with provided values). Since your class already has an insert method, this function doesn't really do anything to justify a separate function.

It's also inflexible in that it only takes input from cin and also unconditionally writes to cout, so you can't automate this process such as accepting input from a file silently.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

From my experience thus far, Windows 10 is fine on a desktop, but frustrating on a tablet. In particular, the Edge browser is too incomplete to be usable at this point, and I use my tablet largely for browsing the web.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

program accepts big_boy_counter and lower_bound_of_big_boy_counter as int*. You then pass the address of those to declaration_list, which makes them both int**. But declaration_list also expects int*, which means you're passing a value of incompatible type.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@deceptikon I'm using C not C++ :(.

Sorry to disappoint, but you're not. C does not allow multiple functions with the same name, overloading is not a feature current or planned for C. If you're allowed to create overloaded functions, you're actually compiling your code as C++, even if for the most part it looks like C.

Or you're depending on a compiler extension, in which case it's technically neither C nor C++. ;)

However, if you want to keep pretending, then the correct solution is as I stated before. rubberman's suggestion will also work in this specific case, but given the declaration for your other overloads I'd hazard a guess that you also want functionality which this trick isn't safe for.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The array to pointer conversion you're probably familiar with only applies to the first dimension of an array. The only solution here is to dynamically allocate the strings as well such that you originally have a char**:

char **strings_like_tokens = malloc(503 * sizeof *strings_like_tokens);

...

split_string(line, strlen(line) + 1, strings_like_tokens);

char** and char*[503] are not compatible types.

However, since this is clearly C++ (C does not support function overloading), good God please use std::vector<std::string>. You'll thank me for the time saved managing memory. :D

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm not sure of the rationale behind not allowing VLA (variable length array) initializers

It's a combination of not complicating the compiler and not hiding an extremely volatile runtime task behind benign syntax. Even in C99+, VLAs are risky and not something I'd recommend using. Robust code shouldn't use them, as failure to allocate cannot be recovered from. A solid solution would still use the gamut of VLA, static array, and dynamic array, so cutting out the VLA part would actually simplify code.

you should consider using calloc instead of malloc

I'm torn between saying "no" and "hell no". The problem here is that an array of pointers is being allocated, and calloc encourages a false sense of security that those pointers are initialized to NULL. NULL need not be synonymous with all bits zero, which is what calloc does.

Otherwise, kudos for a good post. You get my upvote. :)

Blake_2 commented: How do I edit my post on here? I see a major typo and I want to include the calloc thing you mentioned; I wasn't aware of that! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It could be the Framework or it could be how it has been implemented by my predecessor

It's the latter, almost surely. The Entity Framework most certainly has its quirks, but being unstable and slow are not among them when used properly.

So I'm wondering if there is a way to just take the entity part out and build an old fashioned data layer with views and stored procedures...

It rather depends on the design, and I suspect the design is fairly entrenched in EF weirdness. My personal preference is to use more of an ADO.NET approach with EF to facilitate database compatibility, but that's not really at issue here. I suspect you're stuck optimizing a poor design. Sorry.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This is C right?

With any luck it's C++ as best practice in C is to specify void as the parameter list. But yes, there's no termination condition in declaration_list to stop the recursion, so it'll go until the machine says "uncle".

rubberman commented: IE, the stack overflows! +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What books would you recommend for data structures and algorithms in C language?

I often recommend Algorithms in C by Robert Sedgewick. The concepts are well written and researched, and this is the biggest benefit of the book. A subtle benefit is that the code is both horribly formatted and severely broken. Fixing it is an excellent exercise for a budding C programmer. ;)

It would be good if recommended books are books of solved problems.

I'm not sure I understand this requirement. Could you elaborate?

Try this:

Lovely, a seminar that pushes C as a road block to C++, Java, and C#... Personally, I'd rather have a book or site that treats C as a real and unique language, which it is. ;)

And this: Six Fast Steps to Programming in C

Okaaay. Let me guess, you wrote that. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Any reason why you would do it one way over the other?

Three words: don't repeat yourself. Saying if (x == true) is redundant. The context alone tells you that x represents a boolean. If you're being redundant "just in case", then would that be an argument for stuff like this?

if (MyMethod() == true == true)

;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problems I guess would be navigating from a language with a certain feature to a language without a certain feature

That's one problem, yes. Another would be choosing a consistently compatible translation route when the target language has multiple ways of doing the "same" thing that in practice may not be the same as the source language. Another might be performance concerns of compatible translations where you don't want the obvious translation because it's hideously slow. Security concerns also vary between languages.

All in all, translating a program between languages tends to be far more complex than it initially seems. It requires intimate knowledge of both, and often there are parts you simply cannot convert automatically without some manual intervention to resolve conflicts.

overwraith commented: Good observations. +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

or cracker are going to crack it easier, steal people's data and people will start disregarding software as unsafe.

Here's my take on it: insecure software will be insecure regardless of code availability. Open source certainly makes insecure software easier to crack, but the underlying problem isn't being open source, it's being insecure.

The fix is not to implement security by obscurity and hope crackers aren't smart enough to dig into the binaries, the fix is to correct security holes. And for that goal, open source is potentially superior as there can be more eyes on the code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm probably a glutton for punishment, but are threads just a bit easier to follow now?

thumbsUp.jpg

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

'Lil bit, yeah. It's not a deal breaker, just something that takes getting used to.

  • I think the signature is out of order. You see the post content first, then who posted it. Would I be correct in guessing that you wanted us to view posts on their merits rather than filtering by posters we trust? ;)

  • The signatures are busy, which seems to make the posts themselves get lost in the mix. For longer posts it's not a problem, but posts with a few lines or less are easy to miss.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You've found one problem with atoi. Please read this for more.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

unsigned long hash(char** str )
char *str[9]={...
key= hash(str[i]);

One of these things is not like the others. If you're not compiling at the maximum warning level, you should turn it up now, because the compiler should point this out for you.

I'd also note that your hash algorithm is hideously inefficient and contains a memory leak.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think this is an old micro-optimisation thing that is irrelevant with modern compilers.

It was irrelevant even in prehistoric times too, unless you were working with one of the dumbest compilers ever. Even Dennis Ritchie's first C compiler performed this optimization.

However, note that the type of i matters. For int (or any built-in type, generally), the two are functionally identical. For class types that overload the ++ operator, the prefix version will likely be slightly more efficient.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'd start by putting the database update logic into a few key events for the DGV, such as Validating. But keep in mind that with a real-time update, you need to be very robust in handling DGV errors.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's probably a timing issue. I've encountered similar issues when things happen too fast between closing the file and trying to delete it. A workaround would be to retry the deletion a few times after a short pause:

public static bool SafeDelete(string path, int tries = 1, int wait = 300, bool throwOnFail = false)
{
    // Sanitize the retries count
    if (tries < 1)
    {
        tries = 1;
    }

    for (int i = 0; i < tries; i++)
    {
        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            return true;
        }
        catch
        {
            if (i < tries - 1)
            {
                Thread.Sleep(wait);
            }
            else
            {
                if (throwOnFail)
                {
                    throw;
                }
            }
        }
    }

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

Does this have anything to do with James' new house? Are we hosted in a grungy suburbia basement!? ;p

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What do you think?

I think you have an overinflated opinion on the power of OOP. C still doesn't have OOP[1], and it remains a very popular language. Further, nothing about your requirements suggests that OOP would solve any problems, though it might create some. ;)

cannot get a simple program to operate as desired!

What's the format of your file? That will be the deciding factor in how difficult it is to parse. Personally, I'd prefer a relational database for this, but having a file as your database isn't irrational for a relatively smaller number of records.

[1] It can be simulated in C, but the language doesn't have direct support like C++.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You just said exactly the same thing, with the same non-conventional term. Show me a code example of what you think a "general property" is. Then I'll tell you what the difference is between them and auto properties.

I'd rather not assume what you mean, give a good answer, then have you shoot back immediately that it's not what you wanted.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Example please. While I can guess what you mean, you're not using conventional terms.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Actually, in C++, you can use C functions, or C++ stream functions, including doing things like turning off echo in input streams, so you can do the mapping of input characters to things like '*'.

Do tell. Unless something has changed that I'm not yet aware of, this couldn't be done without depending on behavior provided by whatever shell is active.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Not enough information. Sockets have an easy and obvious way to set the port number, so I can only assume you're asking for something more involved.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Try using System.DbNull.Value instead of vbNull. vbNull doesn't represent what you think it represents. ;)

Santanu.Das commented: perfect suggestion +5
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

While I haven't personally hit that case (I'm neurotic about my own check-ins and thoroughly review anything I take from elsewhere), I have seen it with libraries. We had a utility library that contained a bug in XML serialization that was intermittent and not caught for over a year. By the time I found it, the library was used in a number of applications that then needed to be rebuilt and reversioned, with a not insignificant amount of effort for us and our customers. Bad times. :(

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I always thought I had been programming in C++ :/

You have (probably). But it gets interesting when extensions and libraries are thrown into the mix. Here are the high level options:

  • Standard C++: Only uses libraries and features clearly defined by the ISO standard document. It's highly portable, but quite limited.

  • Compiler-dependent C++: Only uses libraries and features supported by the compiler. This often includes standard C++, but also has extensions to the language as well as extra libraries to make your life easier. The potential problem is you're limited to that specific compiler, and sometimes even that version of the compiler.

  • Platform-dependent C++: Uses standard or compiler-dependent C++ coupled with the APIs offered by the operating system. You may or may not be limited to the compiler, depending on what OS libraries it supports, but in general platform-dependent code is more portable than compiler-dependent code.

  • Third party libraries: Any of the above can be used with them, but you're limited by what the library itself supports.

In the case of getch, it's a compiler-dependent function. So while your code might otherwise be standard C++, using a function that isn't defined by the standard document means your code's portability is affected.

However, since the standard is limited, there are things you simply can't do with standard C++. Raw input is one of them. If you need it, you have no choice but to find a non-portable solution. But in those cases, determining how portable you need …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You could just ask the questions and see what answers you get. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It is not common to use a messagbox in a console application, that's why the reference to Forms is not included by default.

A library project doesn't reference System.Windows.Forms by default either, but it's very common to define form components in a DLL. I'm not convinced the default references are a good argument for what you should and shouldn't use in a particular project type.

Console applications are somewhat rare relative to Forms, WPF, and library projects. However, it's not as uncommon as you might think to mix console and GUI stuff. A more realistic example than MessageBox would be OpenFileDialog or a custom form in a test project.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I am missing something in pointers?

Yes. Pointers have both a value and a type. The value is the address you're talking about, but the type says how you can use the pointer without a cast. The type of your pointer is an array type, so it's unreasonable to expect it to be compatible with a non-array type.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

p is a pointer to an array, not a pointer to an element of the array. You'll need to dereference the pointer, then treat the result like an array:

printf("%d\n", (*p)[1]);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I hadn't built any fault tolerance in.

Not a good habit to get into. "What if this fails?" or "what if the user doesn't enter what I expect?" are key questions that should be answered very early in development. Otherwise you'll end up with brittle code. Further, adding error recovery after the fact often results in subtly broken (ie. did you miss an error case?) or terriby kludgy code (the dreaded band-aid approach).

As an example, I've been asked to refactor entire projects to include robust error handling and logging where it wasn't present before. Most of those projects needed extensive rewriting and in some cases full rearchitecting to do it satisfactorily. At least one project comes to mind where I decided to throw away all of the code and start over; it was that difficult to add what management wanted.