deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your else clause is missing braces. That only works when the body of the clause has one statement, yet here you have (presumably) three.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

can you please tell me which are those

newarr in main and newarr in extend are two completely independent variables. They contain the same value originally, but then you replace the value in extend with the result of malloc. That memory block is neither returned back to main nor freed, so it's a memory leak.

Worse, because it's not returned to main, newarr in main remains uninitialized and any attempt to dereference it is theoretically a segmentation fault.

why Valgrind couldnot find them?

Good question. Valgrind should at the very least be able to tell you that you make two calls to malloc yet there are no calls to free. My guess would be that it wasn't running memory checks.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There are a few problems, and most of them stem from misunderstanding pointers.

On line 12 you have this:

while(i <= cnt)

That's an off by one error. Arrays are 0-based in C, which means if the user enters 3, you're processing the indexes 0, 1, 2, and 3 rather than just 0, 1, and 2. It should simply be while (i < cnt).

if (arr[i++] == 0) *zeros++;

This is the first pointer related problem. *zeros++ will dereference zeros, then increment the pointer, not the pointed to value which is what you really want. Precedence and order of operations can be a little confusing when pointers are involved, but you can do either (*zeros)++ or switch to prefix increment with ++*zeros to get the correct behavior. Also note that you never initialized *zeros to 0, so its value is garbage.

The zero check also contains an off by one error in that you neglect to check the first value in arr by both incrementing arr during input, which is prior to the zero check.

I'd also question what the point of making zeros a pointer here as you could just use a straight up int and return that rather than mucking about with malloc and a pointer.

Finally, the global cnt smells bad. You should avoid global dependencies whenever possible, which in this case it most certainly possible by passing the size of the array as a parameter:

int readInts(int *arr, int cnt)
{ …
ddanbe commented: Nice work done here! +15
Slavi commented: kudos +6
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Well, one thing that stands out immediately is C isn't so pretty that it allows commas in a large number. In fact, if you're exceptionally unlucky (which it seems you are), including them will be syntactically correct but semantically bonkers.

gusano79 commented: aaaand how did I miss that? +10
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Nesting functions is not supported in C++.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The two primary problems are that head is never updated in main, and your output loop never sets stdPtr to stdPtr->next. Given your description of the problem, as well as syntax errors, I find it difficult to believe that the provided code is the same code that you're executing.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Agreed with Moschops, but this is still a legitimate question.

When does it become necessary to allocate memory for an array?

Typically when the size of the array is unknown until runtime, or the lifetime of an array would be insufficient for your needs (such as returning a locally generated array from a function). Another reason might be that the array is large enough to risk overflowing the stack, but in that case you probably need to consider other data structures.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your fabulous prize is being listed on the day's leaderboard. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

They changed the Recycle Bin icon? That's my favorite feature, and the only reason I use Windows! That's it, I'm officially and irreversably moving to Minix. This travesty cannot be be reconciled. Who does Microsoft think they are? Geez!

stultuske commented: ^_^ +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Write code. Lots and lots of code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

so this is not language dependent right?

After a fashion. It's a language-dependent optimization, but it is very common. I would default to assuming that string literals are shared since that's a safer assumption in the general case.

in C also i am getting same results

Yes, C and C++ share roughly the same rules for string literals.

so optimisation will be always done for string literals..

It's not a guaranteed optimization, but I don't know of any modern C or C++ compilers that don't implement it.

they always reside in read only memory..

Yes, this is effectively required by both standards. A compiler can store string literals in read-write memory, but you're not allowed to take advantage of that in portable code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's a compiler optimization. Given that string literals are read-only, there's no reason to create two separate instances of the same string literal in memory.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'd just escape it:

string[] items = str.Split(new char[] { '°', '\''});
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

if the str were to be an array of two dimensions, eg. str[][] format how would it look like?

In a function declaration, only the first dimension size can be omitted. All subsequent dimensions must have a matching size to the array you pass, so it would be something like this:

int mult(int x, int y, int str[][10]);

If you need variable sizes for other dimensions, this is a case where you'll need to simulate an array using pointers completely:

int mult(int x, int y, int **str);

But that changes how you create and use the "array". A proper 2D array won't be compatible with that function signature.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Typically modern systems will use a cryptographically secure one-way hash to store credentials. Provided the password is strong, coupled with judicious salting, it can be quite difficult to break given only the hash result. Not impossible, mind you, but much more secure than using straight up encryption.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The issue is all the programs I'm making at the moment are boring, they don't serve a purpose really so it's just learning that is the problem.

I understand that only too well. When I was learning, the toy programs to test out new ideas and practice felt empty and boring. That's one of the reasons why I developed an interest in compilers and standard libraries. While I literally burned through three copies of K&R due to them falling apart from constant use, my favorite C book is still The Standard C Library and it encouraged me to write a number of my own implementations.

That obsession with tool building kept my interest when learning. More importantly, it gave me a base to become the go-to toolsmith programmer at work. :D These days I work more with C#, but reading the .NET reference source for fun and using dotPeek to decompile whatever I can get my hands on makes me think that I never lost that initial spark of wanting to look under the hood for seemingly innocuous things and figure out how they really work.

You might try finding a similar niche that keeps your drive going but also promotes your programming education.

00Gambit commented: thanks +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You only update the longest word when it's longer than the current word. If you want the last instance of the longest word when there are multiple instances having the same length, update the longest word when it's equal to or longer:

if (strlen(word) >= strlen(max))
{
    strcpy(max, word);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The bad news is that if you're not digging it this early, hardcore programming probably isn't for you. Casual programming can remain fun, of course, but any push into serious development or even a career doesn't strike me as promising.

The good news is that it can be easy to get burned out, especially if you're pushing hard to learn and don't really have a solid goal. My suggestion would be to take some time off and do other things[1]. When you feel the itch and return to programming, give it a go and if you lose interest again quickly, put some thought into whether you really want to be a programmer.

That's probably not the answer you wanted, but in my experience, good programmers love it to death. You have to to keep up with constant changes, constant learning, and being slapped in the face with errors and bugs at every turn. Real coding isn't pretty, and it takes a certain type of personality to tolerate it for any measure of time.

[1] Maybe a game that's popular with techies and programmers like go.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

To answer your immediate question, printf(" %d",ocean[ROWS][COLS]); should be printf(" %d",ocean[r][c]);. The former is flat out wrong in that officially oceanOne[10][10] does not exist. In practice it does for your compiler, but only because that's the memory location for oceanTwo[0][0]. That's why the first call gives you random numbers while the second call gives you zeroes. However, if you populate the two arrays with other values, the real problem will be more apparent: both calls to printOcean display the wrong thing.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

...

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

According to the documentation, it's the index in the source array at which copying begins. Presumably the underlying question is why is that overload being used when the source index is 0?

The reason is that values from the source are being appeneded to the destination rather than copying to the destination starting at index 0, which is default behavior for the simpler overloads. Of the four overloads you have, only two of them offer the option to begin copying to the destination at a different index than 0, and both of them require a starting index for the source.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Compiler vendors are allowed to add onto the standard C libraries. We sometimes refer to those additions as an extension.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In your KeyPressEventArgs object is a Handled property. Set that guy before returning from the event handler to disable subsequent control logic on the event.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

cout << thingie is symbolic for "send thingie to cout". cin >> thingie is symbolic for "send something to thingie from cin". The angle brackets denote the direction that data moves.

Whether >> and << are the best symbology for the behavior is up for debate, but it works reasonably well in practice.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

getline isn't a standard function, so your book is correct. The problem is your compiler supports that function as an extension, so the easiest approach would be to change the name of the function in your code to something else.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Assuming you're using the Visual Studio designer, what I do is keep part of the default name and replace the useless number with the same tag as the related control. The tag is chosen based on what the controls do or represent. Often if the controls are bound, the tag would be similar to the property or column I'm binding to. For example:

class Login
{
    public string UserName { get; set; }
}

...

Label labelUserName;
TextBox textBoxUserName

...

textBoxUserName.ResetBinding("Text", _login, "UserName");

This way I can easily find controls in the quick search popup. Typically from the code view I don't care as much about the relation between controls as their actual type, so the type is prefixed.

The full name type is verbose compared to something like a Hungarian convention, but the former is easier to remember (not to mention there are variations of Hungarian that can complicate things). I actually like the verbosity as well, in terms of code readability.

In practice, I haven't typically needed the name of label controls. So while it wouldn't be harmful to leave them with the default numbered name, it just feels unclean to me. And clean code is important. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why doesn't this work in C#?

Because you should be using || in your loop rather than &&. With &&, jaar will only be compared to 1582 if TryParse fails, which is somewhat nonsensical.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hmm, either my understanding of CLR integration in SQL Server is woefully out of date, or there's a disconnect somewhere. CLR functions are server side entities. You still need vanilla connection strings and T-SQL in your client application.

So your problem boils down to two things as I see it:

  1. Creating a standalone .NET application that doesn't need an installer or any secondary files.

  2. Defining communication with the SQL Server in a way that doesn't need configuration files yet can still be used universally.

The first is simple enough, provided you can safely assume the target .NET framework to be installed. Just make sure your application doesn't need anything that won't be provided by the framework. The second is harder for obvious reasons, and not friendly to changes, but a good start is enabling remote access to the SQL Server and ensuring it's widely available.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You could count the number of zeroes inside a number N with the following algorithm

And if the number begins with zeroes? What if the number exceeds the range of your numeric type? The best approach to handle input as it's typed is to work with it as a string rather than a numeric data type, like in Stefano's hint.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Ditto cgeier. I'm not a fan of directly managing data sources in Visual Studio; it just feels too inflexible compared to doing it manually with ADO.NET.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

my first question is whether a deck of cards should have a base class of card

It doesn't make sense to me, personally. A deck of cards is not a card, it's a collection of cards, so composition is the better choice over inheritance:

public class Deck
{
    public List<Card> Cards { get; set; }

    ...
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Click the Chat button on the bottom bar. This will open the chat window and reset your pending chats count. It will also turn off the inline chat popup until you receive another chat in your chat box.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That code is weak in that it makes an assumption about the bit representation of characters. In particular ASCII upper and lower case letters differ only in whether the 6th bit is set, so that code ensures that the bit is the same before doing a comparison.

A much better approach would be to do the conversion with toupper or tolower instead as those don't assume ASCII.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This sounds like a variation of a repository library I wrote. The ID structure wasn't quite that simplistic, but the concept is similar. Something like this would be a start for you:

private void buttonLoad_Click(object sender, EventArgs args)
{
    var path = GetImagePath(
        Folder, 
        Convert.ToInt32(numericUpDownImage.Value), 
        ".tif");

    if (File.Exists(path))
    {
        // Load the image
    }
    else
    {
        // Handle no image
    }
}

private string GetImagePath(string root, int imageId, string ext)
{
    int folderId = imageId / 1000;
    int imageId = imageId % 1000;

    if (!ext.StartsWith("."))
    {
        ext = "." + ext;
    }

    return Path.Combine(root, folderId.ToString(), imageId + ext);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how can I use it ??

A "dynamic array" is really nothing more than simulating an array. Once created, you use it very much like a regular array.

how can I allocate and intialize it ???

This will allocate a dynamic array of 10 pointers to int, then initialize the pointers with an increasing value. The values are printed by iterating over the array and dereferencing each pointer. Finally, the dynamic array is freed:

// Allocate
int **a = new int*[10];

// Initialize
for (int i = 0; i < 10; i++)
{
    a[i] = new int(i);
}

// Use like an array
for (int i = 0; i < 10; i++)
{
    cout << *a[i] << '\n';
}

// Release
delete[] a;
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It depends quite a bit on the contents of your file. Let's say that the file looks like this:

resistor
inductor
capacitor
diode
transistor
circuit

Then you would replace your push_back calls with something like this:

ifstream in("words.txt");

if (in)
{
    string line;

    while (getline(in, line))
    {
        words.push_back(line);
    }
}

It would be easier to show you where you're going wrong if your code actually had an attempt to read the file. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You're sorting and printing while building the array, which is not entirely incorrect, but unlikely to display properly. Finish reading the file, then sort and print; you'll get the correct result that way. Here's the corrected code with a few other changes:

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

static void sort_a(void *array, unsigned n);
static int cmpr(const void *a, const void *b);

int main(void)
{
    static const char filename[] = "input.txt";

    char *line_array[1000];
    char line[1024];
    int i = 0;
    int j = 0;
    FILE *file = fopen(filename, "r");

    if (file != NULL)
    {
        while (fgets(line, sizeof line, file) != NULL)
        {
            // Trim the newline character
            line[strcspn(line, "\n")] = '\0';

            // Stop processing if line_array is full
            if (i < sizeof line_array / sizeof *line_array)
            {
                line_array[i++] = _strdup(line);
            }
            else
            {
                break;
            }
        }

        fclose(file);

        sort_a(line_array, i);

        for (j = 0; j < i; j++)
        {
            printf("%s\n", line_array[j]);
        }

        // Clean up your memory
        for (j = 0; j < i; j++)
        {
            free(line_array[j]);
        }
    }
    else
    {
        perror(filename);
    }

    return 0;
}

int cmpr(const void *a, const void *b)
{
    return (strcmp(*(char **)a, *(char **)b));
}

void sort_a(void *array, unsigned n)
{
    qsort(array, n, sizeof(const char *), cmpr);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is it valid to use an integer variable as a condition?

Yes. This:

if (var)

Is logically synonymous with this:

if (var != 0)

Provided var has an implicit conversion to an integer or boolean type, it's perfectly valid and makes for nice shorthand in some cases. In this case, 0 is false and any non-zero value is true.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here is the fix:

for (i = len - 1; i > m; i--, m++) {

I'll leave it to you to figure out why that fixes it, but working through the logic with a small line of text on a piece of paper will help greatly. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

...

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Ok, so I tried to change my class properties as Pritaeas suggested, but this didn't work.

It should work, but it's hard to tell why not without seeing a complete bare bones example that exhibits the problem.

Would this be an appriopriate use of (get;set;)?

Yes. In fact, that would be my default choice for publicly accessible data items:

public class TCard
{
    public int Suit { get; set; }
    public int Rank { get; set; }
}

Though in this case I'd prefer to also write classes or enumerations representing suit and rank, since just using int means you'd end up having to validate and error check invalid values.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That's a pretty simple one. There's no definition of the _Clrscr function anywhere in the translation unit. Visual Studio doesn't come packaged with any form of clrscr as a "standard" library, so you need to consider the following:

  1. Did you declare it somewhere but not define it?
  2. Are you using a third party library that declares it but not link with that library?
  3. Was the code written for a different compiler in a non-standard manner?
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The linked image is nonsensical. Please elaborate on your assignment.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is this WPF or WinForms?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It depend on the compiler designers I guess.

Language designers, rather. Allowing no return statement at the end of a function returning void is a hard rule in C++ that all compilers must adhere to.

Some programmers like to be explicit though, and always include a return statement regardless of what's allowed. One example is main. Despite returning int, a special rule states that you can omit a return statement and it will have the same effect as return 0;. Not everybody likes that rule because it's very niche and feels like an exception (only applies to main) that can cause confusion, so they always use a return statement.

I say, whatever floats your boat. Both are perfectly valid and acceptable. It boils down to personal preference. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

why they put it ??

They're being explicit, I suppose. If a function returns void, there's no need to place a return at the end. Falling off the closing brace does it automagically.

what is the logical meaning of it ??

It means that the function will hand execution back to the calling function, but return no value.

is it the same as (return0;) ??

No. return 0; does return a value, and cannot be used in a function with a return type of void.

shahera.arafat commented: void print(node*head,int id){ node*p; p=head; while(p!=NULL){ if(p->id==id){ cout<<p->id; return; } p=p->next; } cout<<"node doesn't exist"; } this (return;)here,for what did they put it ?:/ +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Put simply, ASP.NET does web pages and WCF does client/server communication.

J.C. SolvoTerra commented: Thank you. +3
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Were I writing something like that, I'd link the web access and application access with a web service.

  • Web Service: WCF
  • Web Access: ASP.NET
  • Application: WinForms or WPF
  • Mobile: Whatever WSDL consumption API is available for the supported language.
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Welp, since ddanbe covered the second error, I'll mention the first. You have a name conflict. The class and method are both called Main. Since the method has to be called Main, change the class to something like Program and the compiler should properly report that your floating-point literal needs a type qualifier.