deceptikon 1,790 Code Sniper Team Colleague Featured Poster

the printf() might not be inside if(), but if() states the condition when partition() will be called (recusrsively).. so doesnt that make the printf() dependent on if() ?

It does, but you're thinking of things in the wrong order. When low and high are equal, the printf() still executes even though the contents of the if statement do not.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm having trouble seeing the individual strings in the watch window when I'm debugging my code. Is there any reason for that?

The debugger probably isn't expanding dynamic strings, which is what std::string uses internally. So what you're seeing are the concrete data members. The actual data of the string is probably represented as an address (like 0x12345678), and you might be able to expand that as well to see the string contents. It really depends on the debugger in question.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problem is a conceptual misunderstanding about pointers, but ultimately it boils down to this:

structure[x][y] = readData;

All of the pointers in structure are pointing to the same array, and that array is constantly changing because you use it as the temporary buffer for input. What you really want are copies of readData, not references to readData. The easiest way to do that would be make structure an array of std::string, not pointers to char:

std::string structure[100][100];

readData should also be a std::string so that you don't have to worry about buffer overflow. It would immediately solve the current bug in your code where getline()'s limit exceeds the size of the array (ie. it should be 9, or sizeof(readData)).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

By the way, it was something wrong when I posted this, so had to put all the text in a code block.

Our code validation algorithm will very likely prevent you from posting when you format your text like a letter or formal prose (ie. leading paragraph indentation) because leading whitespace is how our formatting language recognizes and highlights actual code.

You can (and should!) avoid this by starting all non-code text lines at column zero.

p.s. I fixed your first post. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i dont understand why i get output for cases (step number: 3,4,5 and 8,9,10) when "low" and "high" are equal, where as the if() condition in the partition() block states recursion only when low<high...

That might be confusing if your output were performed inside the if statement's body, but it's not. So regardless of the values of low and high, you're still printing output; the two are unrelated.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your format string is incorrect. The %s will read until the first whitespace, so a literal ':' won't be matched (since it was already extracted) and will cause the fscanf() call to fail. If you want to match it then this would be better (example using the first line):

char temp[80];
int rows;

...

fscanf(infilep, "%79[^:]: %d\n", temp, rows);

Note that temp is an array rather than just a char. It doesn't seem like AD made it clear that your use of a char is very broken. Also note that I included a field width matching the size of the array. This ensures that you don't experience undefined behavior from buffer overflow if the string in the file exceeds the size of the array.

The actual specifier is a scanset. It looks for any character that isn't a colon (including whitespace!), as the '[^' scanset is like a logical NOT. This leaves the colon to be matched by the literal in the format string.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

All members have a one time option to change their name from their profile page. The link is at the bottom and is cleverly disguised as a button labeled "Edit Username".

Mike Askew commented: Damn this sly button, I shall start a hunt for it. +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Ignore the above it would be an answer so it's evil and totally stupid of me to post.

No offense, but this statement makes you seem childish and bitter. Surely you can tell the difference between explaining how const works and posting a complete working program for an obvious homework question, right?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I check the value range of double and long double with vs2010, but it gives me the same value.

Yes, long double is pretty much just a synonym for double to Microsoft's C++ compiler. In fact, Microsoft even recommends against using long double forms of the standard library.

could you please tell me how to use the long double format in vs2010.

The sensible answer is to use a compiler that supports extended precision floating point. You could write conversions to IEEE 80-bit or 128-bit from IEEE 64-bit (the format of double in Visual Studio), but I'd recommend against that if you can avoid it. You could also look for a library that supports extended precision floating point like GMP.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The most basic solution is to wrap the code in pre tags to preserve the formatting. But be careful with C++, because you'll need to remember to escape certain characters like angle brackets and the & operators, otherwise they'll be stripped when the browser can't interpret them as HTML. It's annoying looking at naively posted code and seeing #include with the actual header missing. ;)

You could also wrap the code in HTML code tags. I'm not sure off the top of my head if that will fix the stripping problem or not though, it's something to test.

If you need highlighting as well then there are a number of syntax highlighting options out there such as Google Code Prettify or SyntaxHighlighter.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Maybe you need more coffee? ;)

Heheh. Sadly, coffee has no apparent effect on me. That's why I can drink it like water.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Arrays cannot be compared with the == operator. You really have no choice but to loop over the elements and compare them onesie twosie:

int equal = 1; /* Equal until proven otherwise */
int i;

for (i = 0; i < 5; ++i) {
    if (output_1[i] != output_2[i]) {
        equal = 0;
        break; /* No need to continue the comparison */
    }
}

if (equal)
    puts("are equal");
else
    puts("not equal");

This is assuming the arrays are of equal length, of course.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Also I'm surprised that you are content with just two good shows when the entire season looks like a jackpot. :P

These days I find myself having trouble keeping up with everything, so the shows I look for first are adaptations of manga I enjoyed. Those two are fantastic manga, and it would be difficult to mess them up unless they deviate completely from the original story.

I'm still waiting for W Juliet and Hana Kimi[1] though. One day, one day... ;D

Oh, and I've been reading Baby Steps recently. It's an excellent tennis manga that's more realistic so far than any of the others I've seen. I'm not sure how well an anime adaptation would work given the theory explanations, but the action would be better. ;)

[1] Hana Kimi had a live action adaptation, but it was total crap compared to the manga. The live action stuff tends to have a certain style that doesn't appeal to me.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Tonari no Kaibutsu-kun and Suki-tte Ii na yo are all I need to call this season a home run. Today is a good day for otaku deceptikon-kun. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That can happen when Chrome's zoom amount changes. See if ctrl+0 fixes it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

dx9_programmer's answer is good, but I'd like to add just a couple of things. First, don't call strlen() in the condition of a loop because it's inherently inefficient. strlen() is a function that itself contains a loop, so when you say this:

for (int i = 0; i < strlen(word); i++) {
    ...
}

It's roughly equivalent to this:

for (int i = 0; ; i++) {
    int len = 0;

    for (int j = 0; word[j]; j++)
        ++len;

    if (i >= len)
        break;

    ...
}

If the length of word doesn't change in the body of the loop then it's silly to keep recalculating it. So calculate it before the loop, store it in a variable, then reference that variable whenever you need the length:

for (int i = 0, length = strlen(word); i < length; i++) {
    ...
}

Next is the actual cause of your segmentation fault. The problem is that c doesn't point to a location within word. Rather, c points to a location within alphabet. dx9_programmer explained the reason for the segmentation fault in a slightly confusing way, but I'd like to point out that it's also undefined behavior to take the difference of two pointers when they don't point to locations within the same array.

So while you might be getting a segmentation fault, that's not guaranteed to happen. Undefined behavior introduces 100% unpredictability to your program from the point it's invoked forward. So it's a good idea …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Can someone please explain step by step on how I would figure this out.

http://www.cs.duke.edu/~ola/ap/recurrence.html

"If" would be a simple n

It would be constant since the running time doesn't grow with N in any way.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

when there are no comments even then i cant delete it?

No. You can report it with the "Flag Bad Post" link and a reason stating why you want it deleted. Then a moderator will determine if the reason is...well, reasonable. But posts are typically only deleted based on serious rule violations such as illegal content, being complete spam, or copyright violation. We generally don't honor frivolous requests, but that doesn't mean you're not welcome to make them anyway on the off chance that it will be honored.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This is the syntax for the configuration files of Apache servers. This kind of syntax is used inside httpd.conf, apache2.conf, .htaccess and the files used to configure virtual hosts.

We don't have a highlight mode for that, it's probably interpreting it as XML. But I absolutely agree that producing different highlighted text than raw text is a bad thing, and when I get a chance I'll see if it's something that can be fixed without herculean efforts.

cereal commented: many thanks! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

this just takes in one value, so i cant enter double digit numbers here!

I assumed that's what you intended. If you want to handle multiple digits then you're getting into the conversion stuff that scanf() does. It's not especially difficult for integer types (floating point types are a pain in the booty), but there are niggling edge cases that need to be considered for a truly robust conversion.

However, the core of the algorithm is this:

int stoi(const char *s)
{
    int result = 0;

    /* Positive numbers only! */
    while (*s && isdigit(*s)) {
        result = 10 * result + (*s - '0');
        ++s;
    }

    return result;
}

You progressively get a digit, find it's numeric value (by subtracting the character '0', see if you can figure out why this works), add that value to the result, then multiply or shift the result left by a tens place to make room for the next digit. For the string "123", the trace would look like this:

10 * 0 + ('1' - '0')  // result == 1
10 * 1 + ('2' - '0')  // result == 12
10 * 12 + ('3' - '0') // result == 123
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

No, please check the link, in the Apache configuration file or in .htaccess files this is the correct syntax.

Our highlighter doesn't magically determine that you're using an Apache configuration or .htaccess file and adjust its logic accordingly. So whether it's valid for Apache or not is irrelevant. Is this valid XML? If not then the highlighter could rightfully be choking on malformed syntax.

Of course I still don't think it should be modifying the content, but that would at least explain why it's happening. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

where is union required?

A union is never required, but it can simplify certain tasks such as type punning. An example is from the C standard library implementation in my signature. I use a union for punning between an IEEE double, its 64-bit representation, and a breakdown of the key components (specified by bitfields):

typedef union _real8 {
    unsigned long long ivalue;
    double             fvalue;
    struct {
        unsigned long long mantissa : 52;
        unsigned long long exponent : 11;
        unsigned long long sign     : 1;
    } parts;
} _real8_t;

This saves me from having to use the bitwise operators to break down the value manually such as in this helper function:

/*
    @description:
        Implementation helper for the fpclassify macro for double/long double.
*/
int _fpclassifyd(double value)
{
    _real8_t fpv;

    fpv.fvalue = value;

    if (fpv.parts.exponent == 0)
        return fpv.parts.mantissa == 0 ? FP_ZERO : FP_SUBNORMAL;
    else if (fpv.parts.exponent == 0x7FF)
        return fpv.parts.mantissa == 0 ? FP_INFINITE : FP_NAN;

    return FP_NORMAL;
}

The alternative would be much uglier and harder to infer the intended meaning of the code.

please explain with an example where having union is a better choice than any data structure.

This question is confusing, and I suspect you're using "data structure" to mean C's struct. Keep in mind that "data structure" is used elsewhere in computer science to mean a more general way of storing and accessing data (eg. linked lists, trees, stacks, queues).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i dont get any output for case1 (ie char2shrt()) and case2 (ie int2shrt()).. any ideas on that?

'h' is a modifier to the %d specifier, you need them both: "%hd"

i do get an output for case 3 (ie shrt2int()), but have to work out in binary if its correct or not.

You don't need to fiddle with binary to determine correctness, just look at an ASCII table. Type a character and check the corresponding value in the table to verify. For example, if you type 'a' the result should be 97.

*type* input[40] means what?

It means input is an array of 40 objects of size "type". If "type" is char then you have an array of 40 bytes, if "type" is int then you have an array of 40 integers where each one is 4 bytes (going with your assumption). The size of an array of 40 will always be sizeof(type) * 40. Note that sizeof(char) is always 1, and char corresponds to the system's byte size, so an array of 40 char is equivalent to 40 bytes.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That's weird. It's almost as if our code highlighter is interpreting tags with no content as empty tags. At least for that particular malformed situation (an extra closing tag that was probably added automatically by a "helpful" editor):

<tag></tag>
    stuff
    stuff
</tag>
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Not fair, deceptikon -- giving me rep and taking it back! Positive rep, even as a test, is a good thing! :P ;)

The test was actually to see if you'd get negative rep. Aren't you glad the effect was as I hoped? ;)

On a serious note, I hope you aren't planning on changing the wayt the box and arrows interract. I happen to like the way they work now.

I'd like to make it more clear visually which arrow the box is affecting, not change the behavior.

Oh, and the comment you made was left in my list of rep even after you removed it. That might be a bug...

Yeah, I'll need to look at that. If it's practical to do so, the summary should match what you would see by browsing the posts.

WaltP commented: Thanx ;o} +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hmm that crashes on the very last row if there is a dot.

My example was just that, an example. It's your job to make sure that the concept is properly incorporated into your code, which includes adding error handling. It's pretty obvious that boundary cases aren't covered, and in hindsight I should have added a comment for those who fail to engage their brains before copying and pasting. For example, if you say board[x - 1] and x is 0, what do you think will happen?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you have two non-black spots going in different directions from a cell, then that's an intersection:

bool is_intersection(char board[M][N], int x, int y)
{
    if (board[x][y] == '#')
        return false;

    return
        (board[x - 1][y] != '#' || board[x + 1][y] != '#') &&
        (board[x][y - 1] != '#' || board[x][y + 1] != '#');
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

if (c == ' ' || c == '\n' || c = '\t')

One of these things is not like the other. Look very closely, I'm sure the book didn't mix up operators.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What happens if n is greater than 9?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I kind of remember that I need separate methods for the set and get too that lines 5 and 7 need to be inside of.

Yes, the "..." part is a placeholder for intervening code. Since it wouldn't compile, that's meant to show that this is a snippet. I used it so that I could highlight just the important lines of defining the property and using each of the get and set parts without junking up the example with boilerplate.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
public uint[] BIG_Hash { get; set; }

...

obj.BIG_Hash = new uint[5]; // set

uint[] temp = obj.BIG_Hash; // get

The size is an attribute of the actual attached to the underlying object, not the object reference.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

hm... tried that combonation and it didn't work.

And how are you testing for a correct answer?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

We use a third party library to linkify URLs, and it doesn't handle URLs with embedded parentheses. Handling parens is actually rather tricky because you have to consider parens that aren't part of a URL (like (www.google.com)). We'd also need to integrate the change into Markdown and the editor highlighting so that there's not a disconnect between what you see and what you get (these are wildly different designs, by the way, which complicates the changes). Finally, Dani also doesn't like me fiddling with those libraries because then we'd be locked into a specific version.

That's why it's the way it is presently. ;)

You can fix it by using the Markdown link syntax directly rather than depending on the linkify feature:

(http://en.m.wikipedia.org/wiki/Shebang_(Unix))

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Do you have a more specific question? I'm not keen on writing an exception handling tutorial.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Arrays are an aggregate type, you can't simply use the assignment operator. Copying is performed with the strcpy() function. argv[1] is also a string, so *argv[1] evaluates to a single character. I suspect you meant this:

strcpy(target, argv[1]);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your situation sounds perfect for going to university. You'll have a better idea of whether you want to do something with computers after taking classes and and if nothing else leave with a degree that will help you get a job.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

when i have used extern int i; now it will refer i which is outside or extern to the file . right ? then in the next line, i am writing int i=10; then again there is another i for the compiler. So now which i will be used ? thanks.

If you have two definitions of i in different files then the code will fail to link. If the definition in the same file as the extern declaration is the only definition then the extern declaration will refer to it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So according to you, it it will not work because it is not defined ?

It won't work if it's not defined. It if is defined then it'll work fine because that's the use case for extern.

secondly, isn't this an error as i am saying to compiler that x is defined else where and again i am defining another x, so isn't it a re defintion of x error ?

I fail to see what's so complicated about this.

  • You may have one definition, period.
  • You may have many declarations.
  • Code will not compile without declarations.
  • Code will not link without definitions.

That's all, don't overthink it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If the question is unclear to you, please let me know.

The point of this exercise is unclear to me. Is it just random homework from a teacher who thinks trivia will somehow make you a better programmer? Or do you have an actual real world need?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You'll need to catch and handle the SIGINT signal:

#include <stdio.h>
#include <signal.h>

volatile sig_atomic_t caught = 0;

void handler(int signum)
{
    caught = 1;
}

int main(void)
{
    signal(SIGINT, handler);

    while (!caught)
        puts("Booger");

    puts("Got it!");
    getchar();

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

when i use extern int i; and it is also present in other file, then after that i can use it normally ? right ? like x=10 or int x=10 ? i think after declaring i just need to use x=10 only as i have already specified that it is int and extern. am i right ?

When you say extern int x;, you're saying that x is not defined here. Therefore it doesn't act as a definition at all. Whether a subsequent x = 10; succeeds or not depends on the presence or absence of a definition somewhere else (which may be in the same translation unit).

secondly, we say that declaration don't allocate memory, that means when i am writing extern int x then it will refer that variable present in the other file automatically ?

That's a reasonable statement.

thirdly, will it be wrong to write

No, but it would probably make little sense to do so since a definition is also a declaration.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Are we talking about manipulating clipboard data or catching command line signals (though I'm not familiar with ctrl+v as a signal)?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why is there so little support for plain C++ on linux though? :S

I find it funny that you complain about lack of C++ "support" by the POSIX libraries, then turn around and compare it to the Win32 API (itself a C interface). What makes you think that FindFirstFile()/FindNextFile() and the WIN32_FIND_DATA structure are any less "C" than opendir()/readdir() and the DIR structure?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How big is the chance of such a corruption?

Not big, but big enough for me to question why you're doing a byte-wise copying loop over a network instead of using standard libraries.

The current logic is working, and gives me quite a bit of control, therefore I would not part with it immediatly.

Smells like "not invented here" syndrome, to be honest.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you want to increase the element that you find you would use the post increment operator not the pre increment operator.

The prefix operator is a better practice when the result of the expression doesn't matter. The reason for this is because conceptually prefix increment and decrement are faster due to no need for a temporary. Prefix increment works conceptually like this (not valid C++):

int& operator++()
{
    value = value + 1;
    return value;
}

While postfix increment works conceptually like this (still not valid C++):

int operator++(int)
{
    int temp = value;
    value = value + 1;
    return temp;
}

If you need the result then the difference matters because it's the difference between evaluating to the unincremented value versus the incremented value. But for statements like ++value; versus value++;, the result is ignored. Therefore it's best to use the version that has potential to be faster: ++value;.

For built in types it's largely a moot point because even the first C compiler optimized away the conceptual temporary. I think even Miracle C (the canonical "bad" compiler) performs this optimization. However, C++ introduces user-defined types, where the temporary may not be optimized away. You'll notice that people will recommend prefix increment or decrement for iterators rather than postfix, and this is the reason why.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For updating the ProgressBar

That makes sense, though an equally viable perspective is that each file is a transaction and the progress bar tells you how many transactions out of the total have completed rather than taking granularity into how progress of each transaction. You don't really care about partial files, after all, only complete files. If a file is partially complete then that's an error condition.

My concern here is that manually copying a file introduces risk of corruption that File.Copy() will be more likely to respond to correctly.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

what happents when we say int frequenct[frequencysize] = {} . does it do a thing or if it doesent why should the writer put that bracket open and bracket close

Read the comment for that line. It says "initialize frequency counters to 0". That should give you a hint of what the empty braces do. To be more specific, if you have an initializer where the number of items in the initializer is less than the number of items in the array, the remaining items in the array will be default initialized. So this:

int a[10] = {22, 33, 44};

Will initialize a[0] to 22, a[1] to 33, a[2] to 44, and all other elements to 0 since 0 is the default value for int.

and the second part is ++frequent [ responses[answer]] two things about it first of all what will be ++ and a little talking about it , like which element in array will change ?

Let's simplify first, because using an array item to index another array can be visually overwhelming if you're not used to it (and sometimes even if you are):

{
    int index = responses[answer];

    ++frequent[index];
}

Does that help make what's happening more clear?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

While one says "definition occures once through the program( memory is allocated once ), but the declaration can occur many times.", the other says "This means that the declaration is only one throughout the program but definitions can be many."

The first one is sufficiently accurate and the second one is completely wrong. I suspect the second one was written by someone who doesn't really understand the terminology and is using the wrong terms for the concept they're trying to explain.

Walt's explanation is reasonable, but a somewhat simplified version of how C handles object declarations and definitions. I'd recommend going with two guidelines that remove the special cases and leave you with a very simple result:

  1. All declarations are qualified with the extern keyword and have no initializer.
  2. All definitions include an initializer.

With these guidelines, int x; is no longer an option. It can either be a declaration:

extern int x;

Or a definition:

int x = 10;

Now there's no ambiguity and the two are easy to identify.

x = 10;, of course, is an assignment and completely unrelated to declarations and definitions excepting the assumption that by naming the object there's a declaration in scope and by using the object it's already been defined. ;)

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

Question: Why are you copying bytes manually rather than using File.Copy()?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What do you mean by mature ? Is that means they are excellent programmers ?

It means they're mentally and emotionally stable, capable of putting aside any ego when wearing the hat of authority, and able to make make objective decisions based on a calm judgment of the situation. Basically the usual definition of mature when used to describe ideal authority figures.