K
Kelly B
Flash said:Kelly B wrote, On 15/04/07 17:49:
One obvious mistake is that strlen returns a size_t but %d expects an
int. Since size_t is required to be an unsigned integer type this
guarantees you are doing it wrong. If you are using C99 (and it is
unlikely your implementation fully supports C99) you can use
printf("%zu",strlen(b_str));
Otherwise
printf("%lu",(unsigned long)strlen(b_str));
which will work for incredibly long strings.
It is very important to use the correct format specifiers for printf if
you want to get correct results.
If that does not work post you exact code, the complete program that
shows the problem, using copy & paste rather than retyping. Normally I
would say trim it down to a minimal example, but in this case you are
starting from a minimal program anyway.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void reverse(char* begin, char* end)
{
char tmp;
while(begin < end)
{
tmp = *begin;
*begin = *end;
*end = tmp;
++begin;
--end;
}
}
int main(int argc, char* argv[])
{
char a_str[8] = "abc def";
char *b_str = "abc def" ;
printf("str: %s\n",a_str);
reverse(a_str,a_str + strlen(a_str) - 1);
printf("str: %s\n",a_str);
while(*b_str!='\0')
{
printf("%c",*b_str);
b_str++;
}
printf("\n%lu",(unsigned long)strlen(b_str));
return 0;
}
The printf at the end(the one printing strlen(b_str))prints 0 when the
while loop is used
while(*b_str!='\0'){
printf("%c",*b_str);
b_str++;
}
If i remove the while loop it prints the correct value 7!How does the
while loop affect the value of printf?Seems strange to me!