Skip over navigation

Arrays: Memory

Problems

The Relationship between Strings and Arrays

How to Cite This SparkNote

Problem : Print out the characters in a string str by looping through the string using pointer arithmetic.


char* s;
for (s = str; *s != '\0'; s++) {
	printf("%c", *s);
}
Here we initialize the char *s to the start of the string. Then we dereference s which means that it will grab one char worth of memory from wherever s points to and interpret that memory as a character. Then we use pointer arithmetic to advance the pointer to the memory immediately after the character we just printed. We continue doing this until it runs into the null character. Note that if we were given a string that was not null-terminated we would eventually run off the array. In other words, this code assumes that str is null-terminated.

Problem : Write a recursive version of the function strlen that takes one argument, a char * and returns the length of the string. You may assume that the argument will be a valid, null-terminated string.


int strlen(char *str)
{
	if (str[0] == '\0') return 0;
	return 1 + strlen (&str[1]);
}
Note that you could write this same function using pointer notation instead of array notation:

int strlen(char *str)
{
	if (*str == '\0') return 0;
	return 1 + strlen(str + 1);
}
In the first implementation we get the address of the second character in the string in the first recursive call. Notice that this is the same thing as performing the pointer addition of one to the string that we do in the second implementation.

Follow Us