Module 11: C Language Strings Flashcards
String
an array of characters terminated by a null character ‘\0’
String literal
a string in “double quotes”; a read-only string that cannot be edited once created
Standard C library
library of functions that comes with all C compilers (except for LCC) for your use
Editing a pointer to a string literal
don’t!
undefined results
on some compilers it works (LCC)
on other compilers, the data in the data in the array is treated as read-only or “constant”
character array vs. string vs. pointer to the string
string:
char my_string[] = {‘T’,’o’,’m’,’\0’}
pointer to string:
char* my_string_ptr = “Tom”;
you cannot edit a pointer to a string literal
arrays of strings:
this is an array of strings in C:
char my_2D_array[3][4] = {{‘i’,’\0’}, {‘a’,’m’,’\0’}, {‘t’,’o’,’m’,’\0’}} ;
this is just a 2D array of characters in C (notice no NULLs)
char my_2D_array[3][4] = {{‘i’}, {‘a’,’m’}, {‘t’,’o’,’m’}} ;
Passing a 2D array in C
*Note: absence of row number is permissible in 2D array declaration, but absence of column number is not permissible in 2D array declaration
In reality, our function is receiving a memory address. Dereferencing with [] is automated pointer arithmetic. By providing the # of columns in the 2D array, we are telling the compiler how many rows in memory to advance each time the pointer is dereferenced
3 possible places to store data in C
stack: local variables, arguments, returns
global region: global vars, static vars
heap: dynamic space
strlen()
only counts characters up to but not including the first ‘\0’ although space is allocated as asked for
By providing the # of columns in the array…
we are telling the compiler how many rows in memory to advance each time the pointer is dereferenced using the first [] operator
array of pointers
integer pointer int var[] = {10, 100, 200}; int i, *ptr[MAX]; for (i = 0; i < MAX; i++) { ptr[i]=&var[i]; /*assign the address of integer.*/ }
String pointer:
char *names[] = { “Zara Ali”, “Hina Ali”, “Nuha Ali”, “Sarah Ali”};
Pointers to pointers
often used in C to receive addresses of arrays of pointers to strings int a = 1; int * a_ptr = &a; int ** a_ptr_ptr = &a_ptr; Dereferencing: char I_array[] = {'I', '\0'}; char Am_array[] = {'a', 'm', '\0'} char Tom_Array[] = {'T', 'o', 'm', '\0'} char * array_of_ptrs[3] = {I_array, Am_array, Tom_Array}; char** ptr_to_ptr = array_of_ptrs; ptr_to_ptr[0] => I_array ptr_to_ptr => 'I'
Recall the two strings that we can use inside main() via argv[]