deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think all of your problems stem from re-opening the file in your functions. Opening a file stream in write mode will truncate the file to zero length, so every time you call print(), the data in the file gets wiped out.

One way to fix it without significant changes is open the file in main() just before your second loop, remove the call to open() in print(), and finally remove the call to close() in display():

#include <iostream>
#include <cstdlib> 
#include <fstream>
#include <vector>
using namespace std;

int array[7][4];

fstream file2;

template< typename T > void display( const vector< vector<T> >& matrix )
{
    for(int i = 0; i < 7; ++i)
    {
        for(int j = 0; j < 4; ++j)
        {
            array[i][j] = matrix[i][j];
            file2 << array[i][j] << " ";
        }
        file2 << "\n";
    }    
    file2 << "\n";
}

template< typename T >
vector< vector<T> > get( const vector< vector<T> >& m, size_t n, size_t i, size_t j )
{
    const size_t N = m.size() ;
    vector< vector<T> > slice(n) ;

    for( size_t k = 0 ; k < n ; ++k )
        for( size_t l = 0 ; l < n ; ++l )
            slice[k].push_back( m.at(k+i).at(l+j) ) ;

    return slice ;
}

template< typename T > void print( const vector< vector<T> >& m )
{
    for( size_t i = 0 ; i < m.size() ; ++i )
    {
        for( size_t j = 0 ; j < m[i].size() ; ++j )
        {
            file2 << m[i][j] << " …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm willing to bet that you didn't think the Enter key counts as a character in the stream. Your second scanf() reads the newline from pressing the Enter key, so you're replacing whatever is typed for b with '\n'. Unless you type multiple characters for b, of course.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

scanf()'s %s specifier doesn't read whitespace, that's the delimiter. Since you learned not to use gets(), the proper replacement is fgets(), not scanf().

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The Windows API defines a macro called ERROR, which is replacing your use of ERROR with whatever value is defined. It does the same thing with TRUE and FALSE, which is why in the past I was forced to do annoying things like this:

enum boolean { B_FALSE, B_TRUE };

This is precisely the type of problem that namespaces were meant to solve. Sadly, the preprocessor is its own beast, and a beast it can be. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

sigh

This will work and is correct:

#include <stdio.h>

int main(void)
{
    int a = 5, b = 10;
    int temp;

    printf("%d %d\n", a, b);

    temp = a;
    a = b;
    b = temp;

    printf("%d %d\n", a, b);

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

why one should not use XoR or arithmetic operation to swap number???

Because it's inferior to using a temporary variable, and the original reason for avoiding a temporary variable is totally irrelevant unless you're on a severely memory constrained platform. And by "severely", I mean so much that you actually map out your register usage and design algorithms to avoid stack or heap use. Oh, and this also assumes that you're writing your code directly in assembly because C is just too heavy.

Then how to swap numbers without using temparory variable.

http://en.wikipedia.org/wiki/XOR_swap_algorithm

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

And before anyone chimes in with swaps using XOR or arithmetic operators that they think are clever: your solution is bad, and you should feel bad.

WaltP commented: Nice. And correct! +14
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

ie its a way of identifying words that is independent of the order in which its letters appear.

Yes, pretty much.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Decepticon's solution may be faster or easier than either of these, but I'm ashamed to admit that I don't understand it.

Here's a quickie example to show what I mean. Please excuse the crappy Java, I'm terribly rusty:

import java.util.*;

class Foo {
    public static void main(String args[])
    {
        String[] dictionary = {
            "za",  "zoo", "a",      "aa", "ab",  "an", 
            "baa", "ban", "banana", "na", "nab", "test"
        };
        String word = "abnana";

        for (int i = 0; i < dictionary.length; i++) {
            TreeMap<Character, Integer> freq = new TreeMap<Character, Integer>();

            for (int j = 0; j < dictionary[i].length(); j++)
                freq.put(dictionary[i].charAt(j), 0);

            for (int j = 0; j < word.length(); j++) {
                if (freq.containsKey(word.charAt(j)))
                    freq.put(word.charAt(j), freq.get(word.charAt(j)) + 1);
            }

            boolean match = true;

            for (int count : freq.values()) {
                if (count <= 0) {
                    match = false;
                    break;
                }
            }

            if (match)
                System.out.println("'" + dictionary[i] + "' was found");
        }
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I dont understand the frequency list.

http://en.wikipedia.org/wiki/Letter_frequencies.

If u could please explain the psuedo code a bit?

You're basically just matching at least one of every letter in a given word using the available tiles that the player currently has. All of the words that meet this requirement are words that the player can make with his or her tiles.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think the question is actually "how do I generate permutations?"

"nab" isn't a permutation of "abnana". Permutations can get you closer to a complete solution, but that's not all there is to it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This seems more like a job for a frequency list. You can use a dictionary of characters and counts like so:

for each word in the dictionary
    build a frequency list of each character initialized to 0

    for each character in the letter collection
        if the character exists in the frequency list
            increment the count for that character

    if all counts in the frequency list are greater than 0
        mark the word as a match
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

ancient dragon will you please tell me that what is that problem of '\n' with fgets. i am not getting it from your answer. will you please explain it more . isn't scanf appends '\n' to the end ? please clearify me.

Try it and see. You can't always rely on someone else to explain things to you, often a little test program is sufficient to answer your own questions.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What happens if I removed the "using" word? Will it affect my program?

It would fail to compile...

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You'd probably get a compiler error about implicit conversion between incompatible types.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The cast is defined. The way you use the resulting pointer could be defined or undefined. I wouldn't call it good or bad, but the cast does raise warning flags such that I'd question it in a code review.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The address produced by using arr in value context is then reinterpreted as a pointer to int, which can then be dereferenced to get the value stored at arr[0][0][0]. This particular cast is safe, at least until you decide to iterate over all of the items:

int arr[2][2][2] = {1, 2, 3, 4, 5, 6, 7, 8};
int *q = (int*)arr;
int i;

/* Please don't do this */
for (i = 0; i < 8; ++i)
    printf("%d\n", *q++);

While this type of punning of multidimensional arrays into 1D arrays usually works, it's technically undefined by the C standard.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

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

My bad, I missed that bug too. Instead of comparing against srclen, it should compare i against the size of the result to avoid buffer overflow. But since this is clearly homework and that kind of robust error checking is both unnecessary and would result in further changes to the code, just use the condition to stop at the end of dst:

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

void Problem8(char dst[], char src[]);

int main(void)
{
    char src[] = "This is a source string";
    char dst[] = "This is a destination string";

    Problem8(dst, src);
    putchar('\n');

    return 0;
}

void Problem8(char dst[], char src[])
{
    int dstlen = strlen(dst);
    int srclen = strlen(src);
    char result[60];
    int i, j;

    for (i = 0; i < srclen; i++)
    {
        result[i] = src[i];
    }

    for (i = srclen, j = 0; j < dstlen; i++, j++)
    {
        result[i] = dst[j];
    }

    for (i = 0; i < srclen + dstlen; i++)    
    {
        printf("%c", result[i]);     
    }

    result[i] = '\0';
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It would be hard to read a file if you dont know the size.

Well, it's not a one-liner, but not unusually difficult. I don't disagree that this is a sticking point, but even C++ isn't a good language for string processing. C is even worse at it.

I am trying to find a programming language that is right for me.(Trust me i know how weird that sounds).

That doesn't sound weird at all. I've experimented with some obscure languages in my time. ;)

In your opinion what is a better language. C or C++.

C, no contest. C++ has a few niceties that I miss when working with C (std::string being one of them), but it also has a heaping pile of doo-doo that I don't miss. So the simplicity and elegance of C is a net win, in my opinion.

And is C++ so called OOP really going to be a bigger hit then C?

C++ is already a bigger hit than C, mostly because it makes for cleaner modeling of large systems.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So whats is C equivalent of a C++ string?

There isn't one. You could go out and find a third party string library like bstring, but unlike std::string, you don't have the option of a standard string "class" in C.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In your second loop you have this:

intConcatenatedStringIndex = (intLengthOfSource + 1)

That's wrong, and it introduces an off-by-one error by setting intConcatenatedStringIndex one element too far. You'll have better results (and not an invervening garbage character) by initializing the index to intLengthOfSource without any changes.

On a side note, your excessively verbose naming convention is difficult to read. Compare your code with the following, which is pretty much identical except it uses shorter and more conventional names, and also has minor tweaks to maintain consistency (I also fixed a bug in the second loop's condition where only the latter condition was driving the loop):

void Problem5(char dst[], char src[])
{
    int dstlen = strlen(dst);
    int srclen = strlen(src);
    char result[60];
    int i, j;

    for (i = 0; i < srclen; i++)
    {
        result[i] = src[i];
    }

    for (i = srclen, j = 0; i < srclen && j < dstlen; i++, j++)
    {
        result[i] = dst[j];
    }

    for (i = 0; i < srclen + dstlen; i++)
    {
        printf("%c", result[i]); 
    }

    result[i] = '\0';
}

Finally, guessing that Problem5 really means writing your own version of strcat(), here's an implementation that's a bit more realistic and follows the interface and behavior of strcat() more closely:

char *concatenate(char dst[], const char *src)
{
    char *end = dst + strlen(dst);

    while (*end++ = *src++)
        ;

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

Please post a complete program along with starting values for the variables. I'd make an educated guess that you're dividing by zero, but that's pure speculation given your lack of detail.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

A solution to the trawling through posts seperating sigs from images could plausibly be solved by an option in user config to turn on/off display of such imagery in signatures. So if your not interested in seeing them you wouldnt.

That option is already available, though it also includes hiding avatars along with signatures in their entirety.

I'd like to split it into two separate options (one for avatars and one for signatures) because I personally use avatars as a primary way of identifying members. ;) But given the current restrictions on signatures, that's a battle not worth fighting with Dani to approve. At present the hiding feature is really more for page load performance than anything.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What are the for/against's for such implementation on the site? Assuming database related or the content that the less mature individuals would put in the signatures.

Signatures are limited in size so that they aren't obtrusive and take away from the thread. I've been on a few forums where images were allowed in signatures and you could have a 20 line signature on top of it. It was all very distracting when trying to separate the content of posts from flashy signatures.

There really aren't any technical issues for allowing images beyond adding that feature to the profile editor. Images aren't stored in the database as blobs or anything, we keep them in the file system and store references. Displaying them is a trivial matter, and we've already done the work of uploading and embedding images as part of the post editor (so it's a fairly simple port).

Any hesitation about adding this feature would be potential for abuse versus benefit to the community. While I'm not against image signatures and might actually use them myself, I honestly can't say whether such a feature is worth the effort. I can't recall seeing any requests for it other than yours in over 7 years here. Then again, my memory isn't exactly stellar. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Put simply, if the application isn't intuitive, people won't use it unless they're forced to do so. If they need to refer to a manual, the application isn't intuitive. If they need to go to a class, the application isn't intuitive.

In your shoes, my first line of attack would be to shadow users as they actually use the application to accomplish real work, since they're clearly either too timid to complain or not interested in using the application in the first place. I wouldn't offer advice beyond answering pointed questions, just take notes on where they seem to be having trouble. From there I'd have a better idea of what needs to change in the user interface to make the application more friendly.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@deceptikon..then why dont the first code is working without allocating the memory?

The pointer is being assigned the address of an existing array.

my basic ques is do we need to allocate memory to a pointer before using it?

You need to ensure that the pointer points to memory that you own.

i mean in my first code why dont we malloc 'b' before the (b=a) statement?

Because that's unnecessary and would cause a memory leak. The b = a statement is sufficient to meet the requirement of pointing to memory that you own.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What compiler are you using?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So, in the float case statement, it will give unexpected o/p? Reason : I am using int (age) at that time. right ? for making this correct also, i should write

e1.salary=101.45f;
or something like that and then use printf statement for this. am i right ?

Yes.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

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

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

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

#include<stdio.h>

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

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

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

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

    return 0;   
}

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

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

#include <stdio.h>

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

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

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

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

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

    return 0;
}

There are two common fixes:

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

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

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

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

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

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

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

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

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

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For what purpose would you want a constant union? Anyway, you can initialize a union to the first listed member prior to C99, and you can use a designated initializer for an arbitrary member in C99 and later.

/* Earlier than C99 */
const union emp e1 = { "doodage" };

/* After C99 */
const union emp e1 = { .age = 45 };

But once again I'd question why you're declaring a union to be const when the entire point of unions is reuse of a single block of memory for multiple members when those members aren't needed simultaneously.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but here i require to allocate memory to b. why is so?

Where did you think the memory would come from? Pointers don't magically point to infinite memory on declaration, you have to point them to a block of memory that's allocated for that purpose, either through dynamic allocation (malloc and friends) or by assigning the address of an existing object.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

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

So this means these statement will give wrong result

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

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

Yes, that's it exactly.

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

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

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

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

#include <stdio.h>

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

    putchar('\n');
}

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

    foo(pa);

    return 0;
}

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

One last thing,do we need to learn any other subjects to develop a software other than just the programming language..??

Yes, you need to learn general programming theory and problem solving. The rules of the language are easy to learn, putting them together into a functional, robust, and useful piece of software is much more difficult.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

#include <stdio.h>

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

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

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

    return 0;
}

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

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

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

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

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

size_t //Eerm, what is size_t?

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

string s;

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

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

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

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

...

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

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

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

...

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

We could probably do it dynamically with a profile setting, but I think Dani is very much against plain text in the editor given that its highlighting capabilities are one of the primary reasons we chose it.

Is there anything broken with the highlighting such that you want to turn it off (I can try to fix bugs), or do you just not like it?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

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

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

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

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

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

Good hackers know how to program their own exploits and tools. Bad hackers, also known as script kiddies, mindlessly use exploits and tools written by good hackers. This is all using the negative connotation of "hacker", by the way.