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!