Strings

Allocating

char *StrPtr = new char[41];

Freeing

delete[] StrPtr;
  • The behavior of calling delete on an array without the "[]" is undefined.

sizeof, strlen

  • Sizeof behaves differently on an array of characters than on a pointer to a string
  • Strlen behaves the same in both cases.

Examples

char StrArray[41] = "hello";
char *StrPtr = StrArray;
int i;

// different result for sizeof
i = sizeof(StrArray); /* 41, the size of the string */
i = sizeof(StrPtr); /* 4, the size of the pointer to the string */

// same result for strlen
i = strlen(StrArray); /* 5 */
i = strlen(StrPtr); /* 5 */