Download presentation
Presentation is loading. Please wait.
Published byFrank Booth Modified over 9 years ago
1
Charles Clute Tom Most Michael Hein
2
Strings in C There is no String... But there’s hope! Strings are character arrays char volume[6]; char volume[6] = "STRG01"; char volume[] = "STRG01";
3
Creating New Strings Creating garbage strings Creating strings with given characters Creating strings with given characters and size Creating a pointer to a string (dynamic allocation) char str[6]; char str[6] = "STRG01"; char str[] = "STRG01"; char* str = string_name; // no & necessary
4
Characters in strings can be created in two ways: integral values and character literals (surrounded by “'”) Strings in C end at the first null byte (use strlen() to get the length) Null character: str[0] = 'S'; str[0] = 0xE2; // hex literals are handy char zerobyte = '\0'; // escape character char zerobyte = 0; // or 0x00 hex
5
String variables have an implied pointer which has special properties: It has the string name (no subscripts) It is a constant (you can't alter its value) The sizeof operator returns the size of the array, not that of a pointer.
6
Strings can be looped though in two different ways: using subscripts and using pointers. Subscript: int i; char str[6]; for (i = 0; i < sizeof(volume); i++) str[i] = '0'; Pointer: char str[6]; char *ptr; for (i = 0, ptr = str; i < sizeof(volume); ptr++, i++) *ptr = i;
7
strtok() Syntax: #include char* strtok(char *str1, const char *str2); The strtok() function returns a pointer to the next "token" in str1, where str2 contains the delimiters that determine the token.
8
strstr() Syntax: #include char *strstr(const char *haystack, const char *needle); The function strstr() returns a pointer to the first occurrence of needle in haystack, or NULL if no match is found.
9
Other String Functions strcpy() — copies one string to another (buffer overflow, ahoy!) strcat() — appends one string to another strchr() — finds a character in a string (there are several others in this vein) strlen() — finds the length of the string (slow!) memcpy() — copies blocks of memory. Fast and safe. memmove() — like memcpy(), but works if the blocks overlap
10
Pointers Function Pointers When dereferenced, a function pointer invokes a function, passing it zero or more arguments just like a normal function. Syntax: void (*foo)(int a); foo = my_int_func; // (no &) Void Pointers A pointer to void is a generic pointer that can be used to hold an address, but cannot be 'deferenced': that is to say, you can't use it with an asterisk before it to update a variable.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.