I was trying to loop through an array using pointers:
#include <iostream>
#include <iterator>
int main()
{
char name[]{ "Abhi" };
for (char* ptr_c{ name }; ptr_c != (ptr_c std::size(name)); ptr_c) {
std::cout << *ptr_c;
}
std::cout << "\n";
}
This results in: Error: Segmentation fault core dumped
However, in the for
loop's condition testing:
for (char* ptr_c{ name }; ptr_c != (ptr_c std::size(name)); ptr_c)
^^^^^^
Replcaing ptr_c
with name
makes it work. Why?
Shouldn't name
decay to ptr_c
anyway?
CodePudding user response:
ptr_c != ptr_c std::size(name)
This condition is never false. If you add a non-zero number to a pointer, the resulting pointer will never equal the original pointer. Hence, the infinite loop overflows the array.
Shouldn't name decay to ptr_c anyway?
No. name
always decays to a pointer to the first element. ptr_c
only starts as the first element, but after the first iteration, it points to other elements.