ECE-1021
HOMEWORK #9
(Last Mod: 27 November 2010 21:38:38 )
Programming Problems #7.(1-4) (p382).
Like the prior homework where you wrote your versions of the character and string functions, you are to write all four of these functions and then use them in a meaningful test program. Since you are only dealing with four functions instead of forty, your test program is expected to be more substantial.
None of these functions should use array notation - meaning that if the grader sees any square brackets in your function code you lose significant points since the whole purpose of this assignment is to work with pointers.
To gain experience with both ways of accessing data via pointer, the first two functions (7.1 and 7.2) are to use pointer/offset notation where the value stored in the pointer is never changed and a variable offset it added to it before the result is dereferenced. The second two functions (7.3 and 7.4) are to use pure pointers meaning that the desired address is stored into a pointer variable and then that variable - with nothing added to it - is dereferenced.
Examples:
Rewrite the function my_strlen() using both means of access:
Original implementation using array notation:
int my_strlen(char *s)
{
int i;
i = 0;
while('\0' != s[i])
i++;
return(i);
}
Implementation using pointer/offset notation:
int my_strlen(char *s)
{
int i;
i = 0;
while('\0' != *(s+i) )
i++;
return(i);
}
Implementation using pure pointer notation:
int my_strlen(char *s)
{
int i;
i = 0;
while('\0' != *(s++) )
i++;
return(i);
}
Alternate implementation using pure pointer notation:
int my_strlen(char *s)
{
char *c;
for(c = s; '\0' != *c ; c++);
return(c-s);
}
Notice the difference between the last two. The first one walks a single pointer up through the memory space until it points to a NUL character while, at the same time, incrementing a counter each time it advances. The second function uses a second pointer, initially equal to the first one, and then also advances through the memory space until a NUL character is found. The difference is that there is no need to increment a second counter variable at each step - which can be a lot if it is a very long string - since the length can be calculated once at the end of the loop by subtracting the address of the start of the string from the address where the NUL character was found.