Hi All

I'm learning C at the moment using Code::Blocks running on Windows 7 (64-bit) and I'm having a bit of a problem with code that I've compiled.

This code works and compiles just fine:

#include <stdio.h>

int main()
{
    char cards[] = "JQK";
    char a_card = cards[2]; /* "K" */
    cards[2] = cards[1];    /* "JQQ" */
    cards[1] = cards[0];    /* "JJQ" */
    cards[0] = cards[2];    /* "QJQ" */
    cards[2] = cards[1];    /* "QJJ" */
    cards[1] = a_card;      /* "QKJ" */
    puts(cards);            /* Print "QKJ" to screen */
    return 0;
}

However, when I try using the char* notation, so as to create the pointer and string, the code compiles just fine (no errors reported), but I get that "Program has stopped working" message from Windows.

Here's the code (note the only difference between this and the previous code is line 5):

#include <stdio.h>

int main()
{
    char* cards = "JQK";
    char a_card = cards[2]; /* "K" */
    cards[2] = cards[1];    /* "JQQ" */
    cards[1] = cards[0];    /* "JJQ" */
    cards[0] = cards[2];    /* "QJQ" */
    cards[2] = cards[1];    /* "QJJ" */
    cards[1] = a_card;      /* "QKJ" */
    puts(cards);            /* Print "QKJ" to screen */
    return 0;
}

As I'm learning this is pretty basic code and was hopeful that someone might be able to confirm whether or not this code is correct. The Code::Blocks IDE is set up to use the GCC compiler.

I figured that this might have been an issue with the platform (i.e. Windows 7 64bit) so I tried running the code again on a Windows 2000 32 bit Virtual Machine and I got simular results (this time the error on runtime was "program.exe has generated errors and will be closed by Windows. You will need to restart the program".

Thinking that this might be a quirk of Windows 7 64bit, I thought that I'd install Code::Blocks on my Windows 2000 32 bit Virtual Machine and recompile, again using the default GCC compiler. Unforunately this yields the same results.

As a learner, this is a bit of a stumbling block for me so any help would be most appreciated... Thanks for looking!

Hi All

I'm embarassed to say that I've figured this out and the reason is that Literal Strings can't be updated, which is why this doesn't run.

I hope that this post between "me and me" is useful for other people learning C!

Thanks :)

The difference is subtle, but significant:

char cards1[] = "JQK"; // Array initialized with the contents of a string literal
char* cards2 = "JQK";  // Pointer to a string literal object

In cards1, you own the object, it's modifiable, and everything is hunky dory. In cards2, you own the pointer object, but not the pointed to object. The latter is not modifiable, and any attempt to modify it will fail[1].


[1] Unless your compiler supports modifiable string literals as an extension, but that's not a safe assumption.

Edited 5 Years Ago by Narue: n/a

This question has already been answered. Start a new discussion instead.