120 likes | 383 Views
Charles Clute Tom Most Michael Hein. Strings and Pointers in C. 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";. Creating New Strings. Creating garbage strings
E N D
Charles Clute Tom Most Michael Hein Strings and Pointers in C
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";
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
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 characterchar zerobyte = 0; // or 0x00 hex
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.
Strings can be looped though in two different ways: using subscripts and using pointers. Subscript: inti; 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;
strtok() • Syntax:#include <string.h>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.
strstr() • Syntax:#include <string.h>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.
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
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.