Pointer Arithmetic

Recall our array notation:

char *s = "HI!";
printf("%c", s[0]);
printf("%c", s[1]);
printf("%c", s[2]);

This is just syntactic sugar for manipulating the pointers as-they-are, like so:

char *s = "HI!";
printf("%c", *s); // Retrieve (*) the data at pointer s 
printf("%c", *(s + 1));
printf("%c", *(s + 2));

Or,

int numbers[7] = {4,6,8,2,7,5,0};
printf("%i\n", *numbers);
printf("%i\n", *(numbers + 1));
printf("%i\n", *(numbers + 2));
printf("%i\n", *(numbers + 3));
printf("%i\n", *(numbers + 4));
printf("%i\n", *(numbers + 5));
printf("%i\n", *(numbers + 6));

Example: Comparisons

Notice this functional code which determines if two integers are equal:

int main(void)
{
    int i = get_int("i: ");
    int j = get_int("j: ");
    if (i == j)
        printf("Same");
    else
        printf("Different");
}

Notice this non-functional code for determining if two integers are equal:

int main(void)
{
    string s = get_string("s: ");
    string t = get_string("t: ");
    if (s == t)
        printf("Same");
    else
        printf("Different");
}

Here’s a functional comparison using strcmp from string.h (provides string-related functions, doesn’t set a string typedef):

int main(void)
{
    string s = get_string("s: ");
    string t = get_string("t: ");
    if (strcmp(s,t) == 0)
        printf("Same");
    else
        printf("Different");
}

Pop Question: Address Reuse

string s = get_string();
string t = s;
t[0] = toupper(t[0]);
printf("%s\n", s);
printf("%s\n", t);

This prints out the same string twice (the user’s input string, but with the first letter capitalized). Why?

If we want a genuine copy of s, we’ll need to use dynamic memory allocation.