deceptikon 1,790 Code Sniper Team Colleague Featured Poster

they are all array notation but char** val is implicite and char* val[] is explicite

It's the other way around. They are all pointers, and the [] option is syntactic sugar to highlight the intention that the parameter is an array. But also note that this equivalence only applies to the first dimension of a the array notation. All subsequent dimensions require a size and represent array types. Consider this:

int main()
{
    int a[2][4];

    foo(a);
}

foo() must be declared in one of two ways:

void foo(int a[][4]);  /* First dimension decays into a pointer */
void foo(int (*a)[4]); /* Explicitly stating the first dimension as a pointer */

It's a common misconception that the double pointer type corresponds to a 2D array, which is false:

void foo(int **a); /* Fails to compile */
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I tried to load the above string in XMLdocument, but I used to receive an exception.

You didn't follow up on the answers from your previous thead about that exception, so why should I bother trying to help again?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is have a configuration in monoDevelop IDE so that the executable file will run into centOS server?

You don't need the IDE to run an executable, you only need to install the virtual machine. Just like on Windows where you'd simply install the .NET packages and don't need Visual Studio.

I really can't help you much more than that as I'm neither familiar with Mono nor CentOS.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

As an avid avatar junkie, why would you want to have the same avatar on different forums? ;)

Just kidding, it's a nice idea. I'd actually never heard of Gravatar though, so I'd have to look into it. There's also the niggling worry about using plugins to off-site storage that may disappear in the future. It's fairly safe to say Facebook will be around a while (for our Facebook login), but having not even heard of Gravatar before there's a little doubt in my mind about its pervasiveness.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Home sick in bed with a cold.

You work too hard. Well, then again it could also be that you just party in the city too often. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is char** val the same as char* val[ ]

Only as formal parameters in a function definition. Otherwise, they're not. I'm assuming we're talking about parameters for the answer to your next question.

when is the formal (char** val) used

I'll use the array notation when I'm absolutely sure that the function is intended to work with an array or simulated array. I prefer to use pointer notation when the object is known to not be an array or whether it's an array is unknown.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why are you using a Textbox? Just use a NumericUpDown control with the default set to 0. Not only will this correct your immediate problem, it also saves you all kinds of trouble in verifying that the "values" are actually numeric.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your best bet is to try running Mono on the machine and hope for the best. However, there's a fairly strong likelihood that your code uses .NETisms not available in Mono and will require modification to port it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I received an exception when I tried to pass the above string.

What exception did you get and which version of the .NET framework are you compiling against? This works for me on .NET 3.5:

using System;
using System.Xml;

public class Program
{
    public static void Main()
    {
        try
        {
            var doc = new XmlDocument();

            doc.LoadXml("\n <div> attrib1=\"test\"</div>");

            Console.WriteLine(doc.OuterXml);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

can you please explain what was the cause of error in original code.

Try reading the original post. It includes a description of the problem: "I know whats wrong though, array is merely pointing to buf, it isnt copying the data from buf, so when the data from buf changes so does array[] since it points to it"

The cause of the error is obviously multiple pointers aliasing a single array when the intention was clearly for each pointer to reference a unique array.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's somewhat amusing how you managed to pick the two worst possible options. gets() is completely unsafe, and the latest C standard actually removed it from the library. scanf()'s "%s" specifier without a field width is no better than gets(). In both cases input longer than the memory can hold will cause buffer overflow. They also do different things in that gets() reads a whole line while scanf("%s"...) only reads up to the nearest whitespace.

The recommended go to solution is fgets():

#include <stdio.h>
#include <string.h>

int main(void)
{
    char buf[BUFSIZ];

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

    if (fgets(buf, sizeof buf, stdin)) {
        buf[strcspn(buf, "\n")] = '\0'; // Optionally remove any newline character
        printf("'%s'\n", buf);
    }

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

only small thingy left here is that in the 2nd method, the one you suggested, the loop is doing one extra iteration at the end.

That's the base case where size is 0. The only reason it's "bad" in this case is because of the debug printf() accessing the array out of bounds, but the algorithm is otherwise correct. If you "fix" the problem then you'll end up with an algorithm that fails to find the smallest value when it's the last one in the array.

The correct fix would be to avoid dereferencing the array until after it's confirmed that recursion hasn't reached the base case:

int findMin(int *arr, int min, int size)
{
    if (size == 0) {
        printf("in findMin() : passed values >> min:%d  size:%d\n", min, size);
        return min;
    }

    printf("in findMin() : passed values >> array:%d  min:%d  size:%d\n", *(arr), min, size);

    if (min > *arr)
        min = *arr;

    return findMin(arr + 1, min, size - 1);
}

But these debug printf() calls should be either removed or conditionally excluded anyway, because you don't want to see them once you're confident that the function works as intended.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What API? Chances are good the answer to your question is yes, but it's a little vague.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

don't even really know Assembly but I think you should ask a question in your post, not just post random code.

It's especially important with assembly because the function of a program tends to be non-obvious. I doubt most of us will know what Lab_Tutorial_1 is, after all. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How does the remove function work in this though?

Given that it's empty, I'd say it doesn't work. Or it does work, but it doesn't accomplish anything useful. ;) As far as what it should be doing, please see this tutorial for more details than I'd be willing to go through in a post.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I know the OP did this YEARS ago, but here's how the function should look for anyone who wants to do this:

Since we're talking about other people who want to do this, a table lookup is the recommended solution:

#include <exception>
#include <iostream>
#include <stdexcept>

inline int is_leap(int year)
{ 
    return year > 0 && !(year % 4) && (year % 100 || !(year % 400));
};

int calcDays(int month, int year)
{
    static const int monthdays[2][13] = {
        { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
        { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
    };

    if (month < 1 || month > 12) {
        throw std::invalid_argument("Invalid month");
    }

    return monthdays[is_leap(year)][month - 1];
}

int main()
{
    std::cout << "\t2000\t2001\n";

    for (int i = -1; i < 15; i++) {
        try {
            std::cout << i << ":\t";
            std::cout << calcDays(i, 2000) << '\t' << calcDays(i, 2001) << '\n';
        } catch (const std::exception& ex) {
            std::cout << ex.what() << '\n';
        }
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Get Turbo C, install it, create a project, and write the code for it. Do you seriously think your question is meaningful?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Give me an example for Serialising Multidimensional array in c sharp.

That's an easy one: you can't do it. Multidimensional array serialization to XML isn't supported by .NET. You'll need to use a different type such as an array of arrays or nested List<>. But once you do that, it's trivial:

public class Program
{
    public static void Main()
    {
        try
        {
            var foo = new Foo(new char[,] {
                {'a','b','c'},
                {'1','2','3'}
            });

            Console.WriteLine(Foo.Serialize(foo));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

public class Foo
{
    public char[][] Data;

    public Foo()
    {
    }

    public Foo(char[,] init)
    {
        int cols = init.GetLength(1);

        Data = new char[init.Rank][];

        for (int i = 0; i < init.Rank; i++)
        {
            Data[i] = new char[cols];

            for (int j = 0; j < cols; j++)
            {
                Data[i][j] = init[i, j];
            }
        }
    }

    public static Foo Deserialize(string xml)
    {
        return XmlWrapper.Deserialize<Foo>(xml);
    }

    public static string Serialize(Foo obj)
    {
        return XmlWrapper.Serialize(obj);
    }
}

This code uses a helper class for doing the serialization because the code is pretty much just boilerplate, and there's not much point duplicating it all over the place except when you have special needs. Here's the helper class (comments removed for brevity):

public static class XmlWrapper
{
    public static T Deserialize<T>(string xml)
    {
        using (var stream = new StringReader(xml))
        {
            var xs = new XmlSerializer(typeof(T));

            return (T)xs.Deserialize(stream);
        }
    }

    public static string Serialize<T>(T obj)
    {
        return Serialize<T>(obj, string.Empty, string.Empty);
    }

    public static string Serialize<T>(T obj, string nsPrefix, string ns) …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Does it make a functional difference or is it just a formatting preference?

It's a formatting preference, assuming I understand your question. C# inherits a C rule wherein if you don't include braces on a compound statement (eg. if, while, or using), the next statement constitutes the body. So you can chain usings like you did:

using (TcpClient clientSocket = new TcpClient(host, port))
    using (NetworkStream clientStream = clientSocket.GetStream())
        using (StreamWriter toOmega = new StreamWriter(clientStream))
            using (StreamReader fromOmega = new StreamReader(clientStream))
            {
                ...
            }

And the functionality is as if you did this:

using (TcpClient clientSocket = new TcpClient(host, port))
{
    using (NetworkStream clientStream = clientSocket.GetStream())
    {
        using (StreamWriter toOmega = new StreamWriter(clientStream))
        {
            using (StreamReader fromOmega = new StreamReader(clientStream))
            {
                ...
            }
        }
    }
}

Because the braces aren't needed for all but the innermost statement (unless its body only consists of a single statement), you'll often see an unindented chain because it tends to look cleaner than the unbraced indented version:

using (TcpClient clientSocket = new TcpClient(host, port))
using (NetworkStream clientStream = clientSocket.GetStream())
using (StreamWriter toOmega = new StreamWriter(clientStream))
using (StreamReader fromOmega = new StreamReader(clientStream))
{
    ...
}

But some people (myself included) feel that this obscures the structure of the code, and prefer the fully braced and indented version.

do the repsonses pile up in a buffer that can be read sequentially like this?

Yes. You might consider using WriteLine() instead of Write() though, so that ReadLine() finds …

Ketsuekiame commented: Unfortunately straight line compound is becoming more popular in the junior devs we get here :( +8
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You only allocated memory for p4. p3, p2, and p1 are all still uninitialized.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Everytime you say new, there should be a corresponding delete. Or better yet, you should use smart pointers to save yourself the trouble of figuring out when and where to release memory or worry about forgetting to do it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, the ArtWork folder exist at that location ("...bin\debug\Artwork") ;

That's not the location referenced by your error.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

sqrt : DOMAIN ERROR
pie = + NAN
what does this mean?

It means sum is negative, most likely.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

if usrnme is wrong and pass is correct, it will say "intruder alert"

If the user name is wrong, how do you know the password is correct? Systems that allow only one user are dumb. Telling intruders that they're using the correct password and only need to figure out the user name is even more dumb. ;)

if both are wrong, it will say "you are not welcome here"

I fat finger my login credentials all the time; it would be disheartening if my software told me I wasn't welcome because I had difficulty typing.

tux4life commented: You're always right, and if you're wrong I wouldn't notice ;) +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

When you get extraneous garbage on a string, the problem is consistently a failure to terminate the string with '\0'. I didn't really look closely at your code, but I'm fairly confident that's the problem, so it should give you a starting point for troubleshooting. Just make sure that every time you have a string, it's terminated with '\0' at the correct place.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Can you please explain how your hash funcion works? The use of the numbers and letter to add to the value a.

It's an integer hash described in detail here. But beware, the design of hash functions is a very deep hole.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

deceptikon: A dispose method should be coded so that it cannot throw an exception, or, if it does, bin out of the application

My comment wasn't about exceptions thrown from within Dispose(). My concern was more general in that all of your calls to Dispose() may not happen if intervening code throws. For example:

bar.Dispose();
Console.WriteLine("bar disposed");
foo.Dispose();
Console.WriteLine("foo disposed");

If the first WriteLine() throws, foo.Dispose() won't execute. A using statement fixes this

using (var foo = MakeFoo())
{
    using (var bar = MakeBar())
    {
        // Stuff that can throw
    }

    Console.WriteLine("bar disposed");

    // Stuff that can throw
}

Console.WriteLine("foo disposed");

by forcing all of the necessary Dispose() calls to execute in a finally statement:

{
    var foo = MakeFoo();

    try
    {
        var bar = MakeBar;

        try
        {
            // Stuff that can throw
        }
        finally
        {
            if (bar != null)
                bar.Dispose();
        }

        Console.WriteLine("bar disposed");
    }
    finally
    {
        if (foo != null)
            foo.Dispose();
    }

    Console.WriteLine("foo disposed");
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Or should I do this (seems overkill):

You should do that. It may seem like overkill to you now, but a using statement (implicitly calls Dispose()) will flush the streams, close them, and dispose of any internally allocated resources. To do it manually would require calling Dispose() manually, which could cause problems in the presence of exceptions.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Think about it, a question being solved 8 years ago (the original poster has not returned for 8 years) is suddenly spammed today by a newbie poster and brings it back even though it is already solved... isn't that a problem?

Spam is a different thing than a newbie posting in a thread that's solved. And even if the original question is resolved, there's no reason why the discussion couldn't be continued if someone else has relevant questions or comments.

Unless Dani, you (deceptikon), and whomever does the programming sets up a way for users to permenantly close their own threads so they don't have to take in anymore solutions

The OP isn't the only one who benefits from a thread.

or have a "timer" that closes threads permantly after a few months of being "dead".

This is what I meant by automatically locking threads.

Wouldn't those be helpful features to prevent spam?

True spam should be reported so that it can be removed by a moderator. Legitimate posts are allowed, and if they're not relevant to the thread should also be reported.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

By any chance is Dani developing a way to permenantly close "dead" threads, to prevent spam?

No, and there are no plans in the future for such a feature. Dani encourages relevant thread resurrection, and I would fight tooth and nail to stop automatic locking because I've seen it done in practice and the result is exceptionally unpleasant. At the very least there would need to be another solution.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Although IMO we should not judge people as "over-sensitive" until we have walked a mile in their shoes.

It works both ways. Don't judge people for being "chivalrous" until you understand their reasons for it. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, my gut reaction was correct. The operator<< signature should be this:

friend ostream& operator<<(ostream& out, GenericList<T> theList);

You'll get an unresolved external error until the function is defined, but the main issue was you were passing the wrong type.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but it creat error in the above line "<<list1"

Are we supposed to telepathically extract the error from your mind?

friend ostream& operator<<(ostream& out, T theList);

This looks odd (T here should be the type of the class), but I'm not confident saying for sure since you provided so little code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

eg. guy running around to the other side of a car to open the door for his girlfriend

I was thinking of this as an example as well, but more along the lines of if she's offended by me showing that I care for her, it's not a healthy relationship.

Doing that for some random woman is different, and I'd prefer not to because it opens a can of worms such as what do you do when there's more than one woman riding? I wouldn't consider opening a car door to be an offensive action in general, but I would find it a little odd if done for someone who's not close to you or clearly in need of assistance.

while ignoring my statement that chivalry is based on the view that women are frail, fragile, weak, and should be treated by men like a crystal vase.

I thought I covered that by suggesting that you're confusing chivaly with male chauvanism. Do you have any references that show the code of chivalry to be "based on" a view of female weakness? Last I checked it dealt with weakness in general, which from the perspective of a trained warrior would include anyone who's not also a trained warrior.

I'm not saying you're wrong about society's views toward women throughout history, but I'm not convinced that the code of chivalry is targeted at or inspired by it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Anybody got any views on this? Is common civility something to be shunned in order to avoid offence?

I was raised to be polite and courteous to all, women and men regardless of age. If someone is offended by that, it's not my problem. If a woman gets offended by me holding a door for her (which I would do for anyone a few steps behind me), my thought is "Fuck you, bitch, I'm just being nice. Don't read too much into it". I wouldn't actually say that because it would be rude, but seriously, can't we all just be less sensitive and accept kindness for what it is?

There's a line, of course. I wouldn't offer my coat to someone except in truly extreme circumstances, and I'd only offer my seat to someone who clearly needs it more than me. But smiling, holding doors, offering a place in a grocery line to someone who has greatly fewer items, these are what I see as common courtesy. It's not about feeling superior, it's about not feeling and looking like a selfish douchebag.

Chivalry is associated with a time in history when women were considered property.

There's some truth to that, though as I understand it chivalry itself was more about honorable knightly behavior. This included respecting the honor of women but wasn't specifically targeted toward women. Perhaps you're confusing chivalry with male chauvinism?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

please contribute if you feel my conclusion is wrong!!

I'll assume that you simply missed my post before saying that. If so, please read my post. If not, please read my post again until you understand it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Does the ArtWork folder exist at that location?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i tried the code by replacing the return type of foo() with float then also the output was 4..So this proves that foo() in sizeof behaves as function pointer..

That proves nothing as the most common size of float is 4 bytes and there's no guarantee that a function pointer have the same size as object pointers. Try using double and you'll probably get output of 8, or char and you'll get output of 1. sizeof in this case is evaluating to the type of the return value.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I want to know that since the sizeof is compile time operator then why does thee above code outputs 4 even though the call to foo() will be made at runtime.

You'll notice that foo() isn't called when used as an operand to sizeof:

#include <stdio.h>

int foo()
{
    puts("foo!");
    return 5;
}

int main(void)
{
    printf("%d\n", sizeof(foo()));
    return 0;
}

That's because sizeof only evaluates the result of an expression, even if the expression contains runtime-only components or would be completely invalid if actually run. Another example is with malloc():

int *p = malloc(sizeof *p);

Dereferencing an uninitialized pointer is a horrible idea, but because sizeof evaluates the result as if the expression were run instead of actually running it, the above line is completely safe and even recommended.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Since you're trying to keep things "clean" (whatever that's supposed to mean here), I'm guessing installing both is unacceptable. I'd suggest that unless you're using some feature in the 2008 version that isn't available in the free Express version, go with the more recent of the two.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Download a reference manual and use it is my advice.

That's too much work when they can just post their problem to umpteen forums with the expectation that some kind soul will do it for them.

I'm not an IT professional, I'm a hobbyist, and I've learned all I know by research, and testing and more of the same!

Even among professionals, you're a rare breed. More and more I find that I can no longer assume that the developers and IT specialists I work with have any clue how to do their job.

tux4life commented: That secures your job position :D +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Technically all you need is the compiler and a text editor. In fact, it's usually recommended that you get comfortable doing everything from the command line before moving to an IDE because the IDE, while more productive, tends to hide things from you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

as long as the new posts are relevant to the topic.

The susggestion takes that into account. We still have issues with people resurrecting threads with new or unrelated questions, or with posts that have no value (eg. "Thanks for sharing!" posts). I wouldn't be surprised if a more naggy approach to notifying people that the thread is old helped to alleviate at least some of the problem.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Thanks for the feedback!

Hmm...seems like its a little more complicated than it needs to be.

Longer perhaps (length and complexity aren't 1-to-1), but I don't think it's any more complicated than, say, your suggested alternative in this case.

Some of your algorithms can be simplified using the algorithms in the string library

Yes, that's certainly an option. Full disclosure, I was totally expecting the first reply to be all "why didn't you use the standared algorithms, noob?" ;D

In fact, I did start with stuff like that, and chose to go with a more manual approach in later drafts because I found the latter to be cleaner and more readable in this instance. I'd call this a case of recognizing that just because the standard library is there, you don't have to use it if you don't feel it's the best fit.

it would make more sense to put it under namespace instead of class, just to follow the idiom.

To which idiom do you refer? There's more than one, and I clearly didn't follow the usual C++ conventions. In fact, one might argue that by taking interface cues from .NET, the "static class" idiom is better here. ;)

Another thing is that this can easily be extended to be handled in non-win32 environment just by changing the reservedChars, pathSeperator and so on.

Agreed, and the only reason it's Windows-specific is I was only 90% sure I could get a fully …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

when i change user.size() in the for loop to a constant variable

Unrelated things are unrelated. The loop is bound to the size of user, but you assume (apparently incorrectly) that reservations is large enough to use any index valid for user.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

By using the at() member function, out of range indices will throw std::out_of_range. So I'd wager i is out of range for the reservations vector given that i is bound to the size of the user vector. Though you've also got some fun looking scope hiding going on with i that may be doing unexpected things.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
scanf("%d", &t);

And

scanf("%d%d", &x[q][0], &x[q][1]);

Notice the ampersand (address-of operator). scanf() requires a pointer to an object, and you were passing some random number which was extremely unlikely to be a valid address in your address space.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Another quickie. This is a basic class for working with Windows path strings. It's based off of .NET's System.IO.Path class, but doesn't contain any API dependencies (and thus doesn't normalize the paths, it's all straight string handling). Methods that I've personally found to be useful are included.

The class is specific to std::string so as to remain both simple and clean.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The enter key is a character too, yet you don't account for it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

A great many programmers do not know what a compiler or a linker is either.

Maybe I'm just an optimist, but I'd challenge that statement with the caveat that "programmer" refers to someone who has seriously attempted to learn programming and isn't a rank beginner. I find it difficult to believe that someone could actually learn C and not know what a compiler is at a high level.