Comparing strings

The following allocates two string buffers and it calls the strcpy_s function to initialize each with the same string:

    char p1[6];     strcpy_s(p1, 6, "hello");     char p2[6];     strcpy_s(p2, 6, p1);     bool b = (p1 == p2);

The strcpy_c function will copy characters from the pointer given in the last parameter (until the terminating NUL), into the buffer given in the first parameter, whose maximum size is given in the second parameter. These two pointers are compared in the final line, and this will return a value of false. The problem is that the compare function is comparing the values of the pointers, not what the pointers point to. The two buffers have the same string, but the pointers are different, so b will be false.

The ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.