






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







18 Strings.................................... D 19 String Functions.............................. D 20 Pointers................................... D 21 Strings and Pointers............................ D 22 More on Pointers.............................. D
CpSc111 – Goddard – Notes Chapter 18
We have used strings with double quotes—these are constant strings. But what about testing and changing strings? In C, a string is a null-terminated sequence of characters; that is, there is a special character—written ’\0’—after the last normal character. The standard approach for a user-created string is to store it inside a character array. In particular, this means that the array must have size at least 1 more than the length of the string. For example, a string like ”happy”, which has length 5, is stored in a char array of size at least 6 as:
0 1 2 3 4 5 6 onwards h a p p y \ 0 irrelevant
Constant strings, like the ones we provide to printf, automatically have the null character added to them. But any user-created string must have ’\0’ explicitly added. To print a string with printf or read a string with scanf, use %s. Note that scanf is passed just the name of the char array (we’ll see why later)—no ampersand. Also, scanf ignores whitespace before the string and treats a whitespace as the end of string. So, if you want to read a string that might have a space in it, you need to read in one char at a time, using getchar().
// stringRead.c // adapted from Jamsa // read a string from user and echo it #include <stdio.h> const char EOL = ’\n’; const int SIZE = 100;
int main(void) { char stringA[SIZE], stringB[SIZE]; int index; char letter;
// read a string using getchar
CpSc111 – Goddard – Notes Chapter 19
You can create your functions to do many things with strings. For standard tasks, there are function in the string library.
Almost all string functions have a main loop that iterates until the end of the string is detected. For example, here is code to compute the length of a string:
int strlen(char s[]) { int x = 0; while (s[x] != ’\0’) x=x+1; return x; }
It returns 5 when called by
char test[] = "happy"; strlen(test);
Or suppose you wanted to convert a string to all capitals:
void toUpperCase(char s[]) { int x; for( x=0; s[x] != ’\0’; x++ ) { if( s[x]>=’a’ && s[x]<=’z’) s[x] += ’A’ - ’a’; } }
Further string functions are available in the string library. But beware! If the array you are copying to is not big enough, then crash: the null-character terminator gets lost. These functions include:
The only one you have to know is strlen.
#include <stdio.h> #include <string.h>
int main(void) {
char alpha[] = "alpha"; char beta[] = "beta"; char final[100];
strcpy(final, alpha); if( strcmp(final,alpha)==0 ) // true printf("%s and %s are the same\n", final, alpha );
strcat(final,beta); // final is now "alphabeta" if( strcmp(final,alpha)>0 ) // true printf("%s comes after %s\n", final, alpha );
return 0; }
int x = 2; int p = &x; printf("%d",p); // prints 2 p = 11; printf("%d",x); // prints 11 x = -5; printf("%d",p); // prints -5 because p still points to x
Incrementing a pointer moves it to the next “cell” in memory. (The actual change in the address depends on the size of the variable that the pointer points to.) This pointer arithmetic is useful in array manipulation. The pointer can be initialized with the name of the array—because the name of the array is equivalent to the address of the first cell. Indeed, the name of the array is a pointer. The following code prints out the array:
int B[] = {1,4,9,16}; int *p = B; // initialize p to point to start of array B for(int i=0; i<4; i++) { printf("%d", *p); p++; }
It is good practice to set unused pointers to NULL (a special constant defined in C to be equal to 0), to emphasize that we know it’s not yet or no longer usable.
CpSc111 – Goddard – Notes Chapter 21
We have seen that in C a string is stored as an arry of chars. It turns out that any block of chars can be interpreted as a string. This block can be accessed via the array name, or more generally, via a pointer. In general, a string function can take as its argument either an array name or a pointer to the first char in the string. Here is another implementation of the function to calculate the length of a string, using pointer arithmetic.
int strlen(char s) { int len=0; while (s != ’\0’) { s++; len++; } return len; }
We can use pointer arithmetic to achieve the same effect:
int strlen(char *s) { char t = s; while (t != ’\0’) t++; return (t-s); }
Here is a further implementation of strlen that uses the fact that the ’\0’ character is equal to zero when used in a calculation. That is, the boolean condition *s is true if *s is nonzero, meaning s points to anything except the ’\0’ character. It also uses the comma construct, which for example allows two statements to be included in the update portion of a for loop.
int strlen(char *s) { int x=0; for ( ; *s; s++, x++ ) // notice the comma ; // empty body return x; }
return 0; }
One can also write code that alters a string. For example, what does the following code do to a string that was defined by char *beth?
while( *beth==’ ’ ) beth++;
It removes any leading spaces. But note that this assumes that beth is stored in an array. If one writes a declaration as char *beth = " happy", the string “ happy” is a constant and not alterable (you’ll get a segmentation fault).
CpSc111 – Goddard – Notes Chapter 22
In C, all function arguments are passed by value. That is, the function receives a copy of the value, and cannot change the original. So while the contents of an array that is passed to a function can change, ints passed to a function cannot change. And yet scanf does its job... The solution is that you can pass the function the address of a variable. For example, a function to swap the values of two numbers uses pointers:
// swaps the values pointed to by a and b void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
The calling code might look something like:
int x,y; // x and y initialized swap( &x, &y );
An array is automatically passed as an address, equivalent to a pointer to the base type.
One can create an array on the fly: this uses dynamic memory allocation. This is espe- cially important for arrays (and more advanced structures) that exist only temporarily. The function calloc is contained in stdlib.h. It reserves/allocates and initializes a block of memory. The function takes two int arguments: the first argument is the number of elements to be stored and the second argument is the size in bytes (think “cells”) of the element that is to be stored (which is obtained using the sizeof). The calloc function returns the address of the beginning of the block.
int *intPtr; intPtr = calloc( 1000, sizeof(int)); *intPtr = 10;