C++ traverse char* array/char**

C++ traverse char* array/char**

wrong way

const char* array[] = {
    
    "This", "is", "an", "array"};
char** address = array;

for (int i = 0; address && address[i]; i++)
{
    
    
	cout << address[i] << endl;
}

Running results Tracking the i
Debug
variable in the for loop shows that i has actually exceeded the number of elements in the array, resulting in an out-of-bounds access

correct way

const char* array[] = {
    
    "This", "is", "an", "array"};

for (int i = 0; i < sizeof(array) / sizeof(char*); i++)
{
    
    
	cout << array[i] << endl;
}

Guess you like

Origin blog.csdn.net/pythonandjava/article/details/124536364