Hi,
why does the following function returns wrong result:Code:int iStrlen(const char *str1)
{
int len =0;
while(len++,(*str1++ !='\0'));
return (len);
}
length for "google"
Output:
6
Printable View
Hi,
why does the following function returns wrong result:Code:int iStrlen(const char *str1)
{
int len =0;
while(len++,(*str1++ !='\0'));
return (len);
}
length for "google"
Output:
6
Why do you consider the output to be wrong? google is six characters in length.
??
Okay i am sorry....
It prints 7 for "google"
It always prints 1 extra....
You are off by one with your len counter. Try something like this:
You were incrementing len before you were checking for '\0'Code:#include <stdio.h>
#include <string.h>
int iStrlen(const char *str1)
{
int len = 0;
while (*str1++ != '\0') {
len++;
}
return len;
}
int main(void)
{
char txt[] = "google";
printf("txt = '%s'\n", txt);
printf("strlen(txt) = %zu\n", strlen(txt));
printf("iStrlen(txt) = %d\n", iStrlen(txt));
return 0;
}
thanks.....Is there an alternative to do the same thing in one line?
Why do you want it as a one liner? Personally, I am not a real fan of cramming everything into one line (depending on the situation). Anyway, you could do something like the following:
Using the for loop tends to lend itself more naturally to this task (though some of the more experienced programmers here could undoubtedly demonstrate a nice way to do the same thing with a while loop).Code:#include <stdio.h>
#include <string.h>
int iStrlen(const char *str1)
{
int len;
for(len = 0; *str1++; len++);
return len;
}
int main(void)
{
char txt[] = "google";
printf("txt = '%s'\n", txt);
printf("strlen(txt) = %zu\n", strlen(txt));
printf("iStrlen(txt) = %d\n", iStrlen(txt));
return 0;
}
thanks....for your time
Why does the following function throws exception:
It throws exception at the highlighted line....what may be the reason?Code:void vRevStr(char *ptr ,int len)
{
int a = len/2,i;
char *c,*d;
d = ptr;
c = ptr +len-1;
for(i=0;i < a;i++)
{
*ptr++ ^= *c--;
*c-- ^= *ptr++;
*ptr++ ^= *c--;
}
printf("string content:%s",d);
}
Thanks in advace
I'm not sure, but you can test it with some printf() lines of code being added, and then step through it and see.
You know that an odd line length won't divide by 2 into equal parts. Does your code handle that correctly? In lines where you are having multiple increments/decrements, post decrements are not always going to work as you'd hope. Be as explicit about the order of operations you want, as possible, and use pre increments/decrements, whenever feasible.
I'd use the while(low index <= high index) kind of logic for the test. Like in a binary search function.
As an aside:
Question 20.15c