Answer the question
In order to leave comments, you need to log in
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;
}
}
}
unsigned strlen(const char *str) {
cout << str+4 << endl;
}
int main(){
strlen("string");
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question