E
E
Evsign2014-09-25 23:47:46
C++ / C#
Evsign, 2014-09-25 23:47:46

Why doesn't pointer arithmetic work?

There is a task where you need to write a function that will return the number of characters in a string, i.e. it turns out you have to count until you stumble upon \0
I did it this way:

unsigned strlen(const char *str) {
  for (int i = 0; true; ++i)
  {
    if (str[i] == '\0'){

      return i;
    }
  }
  
}

But how to do the same, only working with memory?
In trying to figure it out, I stalled at the very beginning.
unsigned strlen(const char *str) {
  cout << str+4 << endl;
  
}

int main(){
  strlen("string");

}

Please tell me where is the error in my reasoning?
"string" is an array of chars.
Because "string" array, then the first element will be pointed to by the variable in which it is contained.
In the context of the strlen function, this would be the str pointer . Those. &str[0] is the same as just str . According to the rules of pointer addition, str+4 must correspond to the address of the memory location of index 4 . Those. the address of the 4th cell should be displayed in 0x form, but for some reason "ng" is displayed instead .
How can I get the address of the 4th cell for example?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lolshto, 2014-09-25
@Evsign

str + 4 is not a character, but a pointer to a character, i.e. typeof(str+4) == char*
cout treats char* as a string, and outputs characters from the beginning of the string to '\0'. In your case, 'n' is output, the next character is 'g', then '\0' is encountered, and the output stops.
If you want to output the character 'n', then you need to dereference the pointer: cout << *(str+4)
When accessing by index, you get the contents of the array at that index, not a pointer to the element:typeof(str[4])==char

str+4 === &str[4]
*(str+4) === str[4].

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question