Hi there,
I have been reading in this group for a while really enjoy this pool
of infinite c wisdom. :)
Anyway, I have question now. I have this little piece of code that is
giving me a headache.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Definitions */
#define STRING_LENGTH 12
/* Variables */
char str[STRING_LENGTH];
char *str1;
char *str2 = &str[0];
unsigned int i;
/* Main */
int main(void)
{
str1 = "Hello World!";
printf("String length: %d\n",strlen(str1));
for(i = 0u; i < strlen(str1); i++)
{
*str2++ = *str1++;
printf("%d\n",i);
}
puts(str);
/* Wait for key */
getc(stdin);
return EXIT_SUCCESS;
}
The problem is the strlen(str1) expression. The code compiles fine
(with latest MinGW under XP) but running the executable it gives me
the following output:
String Length: 12
0
1
2
3
4
5
Hello
It seems to break out of the loop early, after 6 iterations instead of
12.
I replace the expression with something like this:
unsigned int length;
....
length = strlen(str1);
for(i = 0u; i < length; i++)
{
*str2++ = *str1++;
printf("%d\n",i);
}
....
Then it works fine and runs 12 times and copies the entire string.
Any idea whats the problem here?
Thanks,
Chris