What the code trying to do

1
2
3
4
5
6
7
int noname(const char*p)
{
      char *r = (char*)p;
      while(*r!='\0')
      r++;
      return r - p;
}


I not really understand how the code trying to say

It's say that what negative aspects of pointer does this fragment exhibit that makes it difficult to read?

The code calculates the length of a character array pointed to by 'p'. It finds the terminate symbol '\0' and then substructs the pointer to the initial symbol from the pointer to that terminate symbol and gets number of bytes between them.
It would be better to write

const char *r = p;

instead of

char *r = (char*)p;
Last edited on
can provide a example for me?

example i insert a string of

flower
I did not understand what example are you speaking about?

Using of the function

1
2
3
char s[] = "This is an example";

std::cout << "Length of s is equal to " << noname( s ) <<  std::endl; 
Last edited on
Not to be pedantic, but vlad please change the ';' to a ':' in std::cout
@Script Coder
Not to be pedantic, but vlad please change the ';' to a ':' in std::cout


Thanks, I hope I have updated this typo.:)


Topic archived. No new replies allowed.