deceptikon 1,790 Code Sniper Team Colleague Featured Poster

While I'd start by suggesting that you use the .NET file stream options instead, String^ can be converted to std::string using marshal_as if so needed.

Nether_1 commented: This worked, I posted the new code. BTW, I know you can use .NET file stream, but since I'm more acquainted with the fstream system, I used it. +1
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This is clearly a homework or interview question, so please let us know what your thoughts are first.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

zachattack05 : 25 % 2 would return 5

I'm so tempted to write a proof where this actually happens. :D

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

... or use bitwise operator if(i&1) if true even else odd.

I suppose if you want readers of your code to think you're clever, or have legitimately profiled the code for performance, run all practical test cases, and determined that this micro-optimization is warranted and not actively harmful.

Its faster because compare one bit only without mathematics

Citation needed. Compilers are rather smart, often smarter than the programmers who merely think they're smart. Optimizing x % 2 into the suitably fast machine code is rather trivial. If you're applying this optimization with expectations of any noticeable positive impact, I think you'll be disappointed.

In fact, trying to outsmart the compiler can indeed produce slower machine code by bypassing superior optimizations. If it does improve performance for your test cases, there's a good chance the compiler explicitly chose not to optimize it because the results would be flat out wrong.

But let's not quibble over minutia. Instead, how about looking at a far more sinister problem with your suggestion: x & 1 is not synonymous with x % 2. On top of limiting the supported type to integers, the result of the operation varies between the two when working with signed integers. Will it work? Probably...but are you sure? Note that the OP's code is performing this check on values contained in an array. These values will likely eventually be uncontrolled user input. Are you still sure it will work correctly? Can you prove it?

It's unfortunate …

ddanbe commented: Good point. +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Thus c_str() isn't making a copy of anything, globalPtr is pointing to the same array of characters that abc uses and if you make a change using globalPtr or abc, both are affected.

Yup, c_str isn't required to make a copy of anything, and usually doesn't.

returnValue seems to point to I'm not sure where, but clearly it's not pointing to whatever c_str() returned?

returnValue points to the internal buffer of the string object. VS2015's string class maintains a null terminator in the internal buffer to facilitate simple logic for c_str. The destructor also shrinks the string to zero length, which leaves the released memory clean and explains why the output is "" rather than the previous contents of the string.

I'd suspect GCC "works" because it doesn't have this cleaning step, so whatever was at that memory location remains the same while it "fails" with VS2015 because of the truncation in the destructor. Regardless of compiler quirks, the code exhibits undefined behavior due to accessing memory you don't own.

So, calling c_str() is perfectly fine?

Yes.

if temporary object won't exist after enclosing braces of fun(), then callingc_str() should also be wrong. Isn't it?

It would be if the braces of fun() were the sequence point I mentioned. Instead it's the full expression of returnValue = fun().c_str(). When the initialization of returnValue is complete, the temporary is destroyed, not before.

Secondly, when exactly the temporray object be destroyed?

The …

AssertNull commented: Good explanation +6
nitin1 commented: Awesome :) +4
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

when fun() returns, it calls the copy constructor again, right?

Ehh, kind of. Return value optimization is a thing, but conceptually it's okay to think of things that way for simplicity.

But, won't it call the copy constructor and then make the copy of the object and return it to the returnValue variable?

Yes, but the lifetime of that temporary object ends after the enclosing expression's sequence point. The enclosing expression is your initialization statement for returnValue, which is why you can call c_str successfully (ie. the temporary object still exists), but the pointer is dangling at the end of the statement (where the temporary is destroyed), because it points into the temporary object's memory rather than directly owning the memory.

Boiled down, the problem is really no different from returning a pointer to a local variable even though throwing unnamed temporaries into the mix makes it harder to recognize.

nitin1 commented: +1 +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Can you please explain the reason behind this?

You're capturing a direct pointer to the internal storage of the string returned by fun(), which is a temporary object. The temporary object is subsequently deconstructed, and the internal storage goes away. I'd suggest stepping into everything in the debugger to see how your compiler is handling the objects, because this is correct behavior.

returnValue2 works fine as you're copying the temporary object and preserving its contents in a new object.

nitin1 commented: +1 for to-the-point answer +4
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The first thing that comes to mind is to filter out the special value(s): MyList.Where(x => !double.IsNaN(x)).Min().

Though depending on what might be acceptable insertions into the list, you might need to consider things like NegativeInfinity as well.

ddanbe commented: kudos! +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I agree with AssertNull, it's very likely the newline character mucking things up. Your compiler (or compiler settings) probably aren't zeroing out local variables while AssertNull's is, which explains the code working in one place but not another. You can verify this by initializing _artichoke, _beet, and _carrot to 0.

Typically, it's not wise to mix formatted and unformatted input (ie. getchar and scanf) due to differences in handling of whitespace. IIRC, the %d format modifier should skip whitespace before attempting a character extract, though I don't recall if that's a hard requirement or just something that a lot of compilers do (it's been a while since I read the standard ;p). You can force it by putting a leading space in your format string:

scanf(" %d", &_artichoke);

fseek(stdin,0,SEEK_END);

Yeah, that's not guaranteed to work. There's not a complete standard way to "flush" stdin in C; the best you can get is some variation of this:

int c;

do
{
    c = getchar();
} while (c != '\n' && c != EOF);

It's perfectly functional, provided the stream is not currently empty. If it is empty, getchar will block for unnecessary input and there's no standard way to get around that particular issue.

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

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

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

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

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

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

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

Please post the whole of your relevant code. My guess would be the counter is being incremented incorrectly, or the condition of the loop doesn't check the counter the way it should.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The auto keyword is compiler magic from C++11 that interprets the type of a variable from its initializer. It's not a dynamic type or anything, so as an example if you're using v.begin() as the initializer, auto will choose the type of the collection's non-const iterator (in this case vector<vector<double> >::iterator). Really the only difference is you don't have to manually use the type name or worry about changing any use of it if the if the type changes.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

vector<vector<double> >::iterator and vector<double>::iterator, respectively for the nested loops. Just like you're doing with miter, which is why I didn't mention it...

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Forget that you're dealing with miter->second for a moment. How would you display the contents of a vector? We know cout doesn't have an overloaded << operator for collections, so you're stuck with some variant of a loop. This comes immediately to mind:

for (auto it = v.begin(); it != v.end(); ++it)
{
    cout << *it << ' ';
}

Since this is a vector of vectors, you have a nested loop:

for (auto row = v.begin(); row != v.end(); ++row)
{
    for (auto col = row->begin(); col != row->end(); ++col)
    {
        cout << *col << ' ';
    }

    cout << '\n';
}

Now replace v with miter->second, as that's your reference to the mapped vector object.

The idea here is to start with something you understand, then add complexity until you have the final solution that you're looking for.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, but it is imperative that the method accepts a path as a parameter.. I cannot change it.

  1. Get the stream.
  2. Create a file from that stream.
  3. You now have a path.
  4. Profit.
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The file is embedded in your assembly, it has no path. If you want a file you can work with outside of the resource interface, then consider GetManifestResourceStream from the assembly object for a little more control.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Clickie to learn about the difference between a pointer to a function and a pointer to a member function. They're not even close to the same thing.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yep, that looks like a bug in the Markdown processing to me. Markdown can be a little tricky when it comes to lists and code blocks.

In this case, you can double tab the code to nest it underneath the third list item and the block is formatted correctly, or use a dummy line after the list to fully separate it from the code block and continue to use the regular single tab.

Example 1:

  1. One
  2. Two.
  3. Three.

    <?php
    
        Dooby dooby doo
    
    ?>
    

Example 2:

  1. One
  2. Two.
  3. Three.

Blah blah blah.

<?php

    Dooby dooby doo

?>
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

k = n & andmask;

The bitwise AND will set each corresponding bit to 1 if the same bit in both arguments is 1. Otherwise the bit will be set to 0. Since andmask only has at most one bit set to 1, the purpose of this statement is to check the bit at position j to see if it's set.

k will be zero if both bits are not set and nonzero if both bits are set.

k == 0 ? printf("0") : printf("!");

And this statement prints the result of whether the bit is set or not. It's equivalent to the following:

if (k == 0)
{
    printf("0");
}
else
{
    printf("!");
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

char names[100]; - its just a character array which can hold 99 characters and the last one will be '/0'

Yup.

char *names[100]; - All the 100 array elements are character pointers and are pointing to the starting element of 100 names somewhere in the memory location.

Close. Depending on where this array is defined, the pointers could point to nowhere (ie. null) or some unpredictable addresses by default. It's not quite correct to say that they point to names unless you've already allocated memory to the pointers and populated that memory with strings representing names.

if i want to print all those names cout<<*names[i] where i iterate from 0 to 99 will work?

Close. Dereferencing the pointer will give you the first character that it points to, so an iteration loop (assuming the pointers actually point somewhere you own) would be:

for (int i = 0; i < 100; i++)
{
    cout << names[i] << '\n';
}

The reason this works is the << operator knows how to interpret a pointer to char as a string and will do the "right" thing.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is this issued happening because I have "fileName" still open as "objReader"?

Yes.

If this is the case, is there a way to close it while still in my loop?

Well, you could dispose of the reader and break out of the loop, but that's very ugly and prone to error. And I suspect the reason you're asking is you want to continue reading from the reader after moving the file. I'd be more inclined to tweak the logic so that this exclusive access problem simply doesn't exist.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Coolio. Actually, clock is a horrid name because it's also the name of a function in the C library. Your implementation could very easily expose that even if you don't include ctime, so I'd strongly recommend using either a different name or dropping the class in a namespace.

That's most likely your issue. The compiler sees clock as a function rather than a type, so the declaration is malformed.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If that helps.

Not really. What would help is paring down your code to the absolute minimum without eliminating the error and posting it here so we can see what's going down. Typically that error occurs when you have a syntax error somewhere above the line that's reporting it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I would go so far as to say never use rand()

Unless you wrote it, of course. ;) I'm at the point with my C standard library that I use it instead of the built-in standard library for most personal work. rand is implemented as the Mersenne Twister, so I know it's solid at least in terms of the underlying algorithm.

In C++, I agree that there's really no excuse to ignore the <random> library if your compiler conforms sufficiently to C++11.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why is this so?

rand is always seeded with 1 by default, so unless you change the seed with srand, the sequence will be consistent.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

At the very bottom of every page are lists of links, which include the article workshop that's filtered based on your user permissions.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You can't (easily) delete the file while it's locked for reading, so I'd alter the logic so that you break out of the reading loop, destroy the reader object, then delete the file safely.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You must declare int main() and return a value at the end.

Yes to the first part, no to the second. If there's not a return statement in main, 0 will be returned automagically. It's a stylistic choice whether to include a (redundant) return statement for consistency with non-magic functions.

Of course, if the compiler is Turbo C++ then that's all irrelevant since the compiler doesn't sufficiently conform to any C++ standard.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So whenever possible and performance is not an issue you would advise this sort of programming practice?

I wouldn't say whenever possible. Clarity trumps, so if duplicating code makes it easier to understand, that would be my recommendation. And if eliminating duplication is excessively confusing for one reason or another, I'd refrain. But in my experience those situations are somewhat rare if the code is otherwise well designed.

ddanbe commented: OK +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm a little biased as this kind of thing is something I use liberally to avoid duplication, but it's also a good practice in general.

One thing to note though is performance. Refactoring into methods and lambdas does tend to introduce overhead, and you should take that into consideration for the possibility of larger matrices.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Once again, please ask a specific question if you want a specific answer. Managing code seems pretty specific to me, so that shouldn't be a problem for you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think that bothers you looking at my program.

Not really, it's a minor thing. The other problem is very significant.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I see two problems immediately:

char* names;

This represents an uninitialized pointer, not a pointer to infinite available character slots as you're using it. I'd strongly recommend using the std::string class instead. Otherwise you'll need to dynamically allocate memory to that pointer manually for each instance of the structure.

for(int e=20;e<0;e++){

e will never be less than 0, so this loop doesn't execute...ever.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You won't find it here, Daniweb is not a homework service. We'll be happy to help you with specific problems in your code, but we won't do your work for you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

As far as I know covariance and contravariance exist in C# at least as of version 4.0.

This is true, but not for return types from methods.

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

Tried different things myself, but as I'm a still a learner and could find nothing useful on the web, I'm a bit stuck.

It may help your search to know that what you're looking for is called return type covariance. To simplify your search drastically, C# doesn't support it even in the latest version. ;)

There's likely a workaround though, if you specify exactly what you're trying to accomplish rather than simply paraphrasing it for the sake of simplicity.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It works okay for me in Visual Studio after fixing two bugs. First you never initialize listA in main, so the top and bottom pointers are unintialized. A quick fix is this:

listA = malloc(sizeof(list));
listA->top = listA->bottom = NULL;

Second, and a more subtle problem is in buildNode. The logic is fine, but the amount of memory allocated is incorrect. sizeof(node) gives you the size of a pointer, not the size of the _node structure which is what you need. The change is trivial, but not obvious:

node = malloc(sizeof *node);

Now, while you could say sizeof(struct _node), it's generally better not to depend on a type name on the off chance you end up changing it by renaming the type or using another type. The trick above depends on the fact that sizeof does not evaluate the expression itself, only the resulting size. Otherwise, dereferencing an uninitialized pointer would invoke undefined behavior. However, in this case it's both perfectly safe and conventional.

This bug is a side effect of hiding a pointer in a typedef, which is generally not recommended precisely for reasons like this.

Note that I didn't crash in the same place as you did. There's really nothing wrong with printList, so getting an error there is a false positive and one needs to dig deeper in a debugger to find the real problems.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i dont wanna use Third Party Image viewer control

Then your two options have become one option. You'll need to use a third party library to convert the image to a format PictureBox likes. I say a third party library because .NET's built in imaging libraries may likely still cause you problems due to lack of support for the source image type.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your dequeue logic has two major problems:

  1. It does not take into account updating the bottom node.

  2. Wherever the node is deleted, the list is terminated with NULL rather than maintaining the structure if there are subsequent nodes.

This is a basic single linked list deletion, so you might be well served by boning up on linked lists in general.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You've encountered one of the most irritating things about .NET (at least for me): image processing is quite wanting. I don't work with TGA much, but I work extensively with TIFF. The .NET imaging libraries either do not support TIFF readily, such as PictureBox, or the support for conversion of certain types to BMP such that PictureBox would accept it is lacking. A good example is JPEG compressed TIFF. Neither the old style .NET imaging classes nor the much superior WPF imaging classes (which can be used in WinForms) support that compression method.

Long story short, you have two options:

  1. Use a more robust imaging library such as Magick.NET to convert your TIFF and TGA images to BMP so that you can use a PictureBox directly.

  2. Find a third party image viewer control that will support the image types you need.

Either way you'll find yourself using a third party library for the heavy lifting.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problem is that a naive atoi like conversion won't work directly with hexadecimal characters because you need to take into account that a-f represent 10-15. That too requires a minor conversion as well to get the values you need. Once you have those values, this formula works to build a 2 digit hexadecimal value:

16 * first_digit_value + second_digit_value

I like to implement that minor conversion with a string search in the set of available digits. For example:

#include <cctype>
#include <iostream>
#include <string>

using namespace std;

int hex_digit(char c)
{
    return string("0123456789abcdef").find(tolower(c));
}

int main()
{
    char buffer[4] = {'3', '1', '4', 'C'};

    for (int i = 0; i < sizeof buffer; i += 2)
    {
        int digit = 16 * hex_digit(buffer[i]) + hex_digit(buffer[i + 1]);

        cout << (char)digit << '\n';
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hmm. Of the top of my head, I'd say it really depends on what features you plan to support. If there's a huge amount of intersection between the two, I might choose to implement the vector as a composition/specialization of a matrix of 1xN or Nx1. Alternatively, a matrix may be a construction of vectors if that turns out to be more efficient.

I might not even split the two at all and let the caller use the matrix as a vector if there aren't any vector-specific operations (or manually construct a matrix out of vectors, but that seems less useful mathematically).

It's personal preference, of course, but I tend not to rely on inheritance unless necessary. Composition or careful generalization tends to cover most of my needs.

ddanbe commented: Great help. +15