0

Why does this for loop work? (C++ pointers)

Please consider the following: [code] char name[]{ "Mollie" }; int arrayLength{ static_cast<int>(std::size(name)) }; //7 for (char* ptr{ name }; ptr < name+arrayLength; ++ptr){} [/code] The for loop assigns a pointer that points to the first element of name. The pointer is then incremented up to the null terminator of the name. What I cannot understand is how the compiler is interpreting ptr < name+arrayLength as: 'Continue this for loop for as long as the current pointer address is less than the starting memory address + the length in bytes of 7 x chars; essentially the address of the null terminator of name.' How is the compiler implicitly converting 'name+arrayLength' (an array of chars + an int) to memory addresses? I can understand how it would work if I wrote something like "&name[0] + (arrayLength*size.of(char)". However, this would fail unless I had previously declared a pointer to hold this value. The value, say char* endPointer, could then be used for the for loop comparison. What is going on here? Thanks!

7th Feb 2021, 6:17 PM
Jonathan Pollard
2 odpowiedzi
+ 4
Using simply `name` is the same as using `&name[0]`. Why? Because variables holding arrays are actually holding the pointer to the first element of the array. See this example https://code.sololearn.com/cUSyWaKuasVr/?ref=app (Side note: name[0] literally means `*(name + 0)`) Also, adding to a pointer of type X automatically increments it by sizeof(X). So for example, if I add 2 to a `int*` variable, the variable will be point to the memory location with offset 2 * sizeof(int) = 8 bytes from the original location (although in your case, the size of char is 1, so it doesn't really matter). Example https://code.sololearn.com/ceW49173Elyk/?ref=app So in your code, `ptr` points to the beginning of the character array, `++ptr` increments it by 1 each time, which takes it to the next character and finally, `name + arrayLength` literally means (&name[0] + 7) which is the pointer to the end of the array. Hope I was able to explain clearly👍
7th Feb 2021, 8:09 PM
XXX
XXX - avatar
+ 2
@XXX Thanks for your answer - I understand how the pointer arithmetic works - but this still doesn't answer my question: I guess what I am trying to get at is: How does the compiler know that name + arraylength is the memory address + 7 char's worth of memory (say 7 x 4 bytes for a char32_t), rather than name (some memory address) + 7? EDIT: You indirectly answered it here: Also, adding to a pointer of type X automatically increments it by sizeof(X). So for example, if I add 2 to a `int*` variable, the variable will be point to the memory location with offset 2 * sizeof(int) = 8 bytes from the original location (although in your case, the size of char is 1, so it doesn't really matter). Example https://code.sololearn.com/ceW49173Elyk/?ref=app
7th Feb 2021, 9:40 PM
Jonathan Pollard