c-strings joe meehean. c-style strings string literals (e.g., “foo”) in c++ are stored as const...
TRANSCRIPT
C-Strings
Joe Meehean
C-style Strings• String literals (e.g., “foo”) in C++ are stored as const char[]• C-style strings• characters (e.g., ‘f’) are stored in an array of chars• last char is the NULL character ‘\0’ or just plain 0
• A hold over from C• sometimes still used• important to know how they work
2
char ca1[] = {‘C’, ‘+’, ‘+’}; // NOchar ca2[] = {‘C’, ‘+’, ‘+’, ‘\0’}; // YESconst char *cp = “C++”; // compiler adds ‘\0’
C-style Strings• Manipulated using (const) char*
3
bool contains(const char* str, char& letter){ const char* p = str; while( *p != letter && *p != NULL ){ p++; } return( *p == letter );}
cout << contains(“Java”, ‘C’) << endl;
C-style Strings• Standard C library provides functions for C-style strings• int strlen(const char *str)• returns length of str, not including null-terminator
• int strcmp(const char *a, const char* b)• returns 0 if a’s string and b’s string are identical• returns > 0 if a’s string > b’s string• returns < 0 if a’s string < b’s string
4
C-style Strings• Standard C library provides functions for C-style strings• char* strcat(char *destination, char* source)• appends source to destination• puts results into destination• e.g., strcat(“foo”, “bar”) = “foobar”• better have room in destination for
strlen(destination) + strlen(source) + 1 characters• char* strcpy(char* dest, char* source)• copies source into destination• better have room in destination for strlen(source) + 1 characters
5
C-style Strings• Standard C library provides functions for C-style strings• char* strncat(char *destination, char* source, int n)• same as strcat, but only appends n characters• safer version of strcat
• char* strncpy(char* dest, char* source, int n)• same as strcpy, but only copies n characters• safer version of strcpy
6
C-style Strings• Always use these n versions of string copy and concatenate• using strcpy and strcat causes many, many security exploits
• Always remember the null-terminator• strlen won’t work without it• can then cause strncpy & strncat to be wrong
• OR, even better ALWAYS use C++’s string class
7
Questions?
8