Hi,
I have been programming in C for about 6 months now and thought I had got pretty used to it but I came across a weird problem which I don't really understand. I wrote a small program to illustrate my problem (really just a cutdown version of a larger application I am writing).
I am using Windows XP Professional with Dev-C++ and GCC.
Here are two almost identical programs:
Code:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char People[][9] = {
"adam",
"bridget",
"celia",
"claire",
"eric",
"faye",
"fiona",
"holly",
"isobel",
"katie",
"matthew",
};
int ps, pe;
char fs[7] = "hello ";
char fe[7] = "hello ";
srand((unsigned) time(NULL));
ps = rand() % 11;
pe = rand() % 11;
strcat(fs, People[ps]);
strcat(fs, " is here");
printf("%s", fs); getchar();
strcat(fe, People[pe]);
strcat(fe, " is here");
printf("%s", fe); getchar();
return 0;
}
Code:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char People[][9] = {
"adam",
"bridget",
"celia",
"claire",
"eric",
"faye",
"fiona",
"holly",
"isobel",
"katie",
"matthew",
};
int ps, pe;
char fs[8] = "\\hello ";
char fe[8] = "\\hello ";
srand((unsigned) time(NULL));
ps = rand() % 11;
pe = rand() % 11;
strcat(fs, People[ps]);
strcat(fs, " is here");
printf("%s", fs); getchar();
strcat(fe, People[pe]);
strcat(fe, " is here");
printf("%s", fe); getchar();
return 0;
}
They are written in C for a console application.
Now the only difference is that there is an escaped backslash in the strings in the second version (I have also updated the lengths of the strings in the initialisers). The first version compiles and runs fine, displaying two strings such as "hello matthew is here" and "hello adam is here". However the second version displays one of the strings e.g. "\hello eric is here", then it crashes.
I do not understand this error at all.
Please help!