README

Russell J Lowke
Homework Three 

1.

a) output

1073742608 1073742608 1073742611 1073742611 1073742611
536869634 1 49
abcdefg 1073742608 a 1073742610 c
536869696 536869700


b) table

type		name	address		value

char array   x 		536869632   [??? ,??? ,1  ,??? ,??? ,??? ,??? ,??? ,??? ,??? ,???]
char array   y 		1073742608  [a   ,b   ,c  ,d   ,e   ,f   ,g   ,NULL,??? ,??? ,???]
int          a 		536869696   12
int          b 		536869700   1
char ptr     p 		536869704   1073742611

Note: ??? is an unknown value


c)
(i)   p[0]     = d
(ii)  *p       = d
(iii) &y[1]    = 1073742609
(iv)  y[1]     = b
(v)   y + 1    = 1073742609
(vi)  *(y + 1) = b


2.
a)a[2];			3
b)*(a + 2);		3
c)a[4]-a[2]		2
d)a[a[4]-2]		4
e)(a+10)[-8]	3


3.
[1,3,3,4,5,6]
[1,3,6,4,5,6]
[1,3,6,10,5,6]
[1,3,6,10,15,6]


4.
a) *p;				6
b) p[3];			3
c) *((p + 3) - 1);	4
d) p[*(p + 2)];		2
e) *(++p);			5
f) ++*p				7
g) *p++;			6


5. What is the bug in the following loop?

	for (p = a ; p < 6 ; p++)
		printf("%d/n", *p);

	ANSWER: the condition in the for loop:  p < 6  will always return false
			because as p is a pointer address!	thus this loop will not execute.
			and the compiler warns: "comparison between pointer and integer"
	
			
6. What do the following statements print?

a) printf("%s\n", s);				COOKIE
b) printf("%d\n", strlen(s));		6
c) printf("%d\n", strlen(t));		4
d) printf("%c %c\n", s[2], t[0]);	O O
e) printf("%d\n", strlen(t + 1));	3
f) printf("%s\n", ++t);				KIE


7. What is the bug in the following loop?

	for (i = 0 ; s[i] != '0' ; i++)
		putchar(s[i]);

	ANSWER:	a '0' does not terminate the string s.
			Strings are terminated by NULL.
			The condition in the for loop should read  s[i] != NULL

			
8. What does the following print?
			
	for (t = s ; *t ; t++)
		printf("%s", t);

	ANSWER: COOKIEOOKIEOKIEKIEIEE

	
9. Write two versions of strncpy()
	
	ANSWER array version  :

	char * mStrncpy1(char s1[], char s2[], int n) {
		//
		// strncpy copies exactly n characters from s2 into s1
		// -- array version
	
		int i,					  // general purpose counter
		    srcLen = strlen(s2);  // length of s2
	
		// loop n times, copying either chars or nulls
		for (i = 0; i < n; i++) {
			if (i < srcLen)
				s1[i] = s2[i];
			else
				s1[i] = NULL;
		}

		return s1;
	}


	ANSWER pointer version :
	
	char * mStrncpy2(char * s1, char * s2, int n) {
		//
		// strncpy copies exactly n characters from s2 into s1
		// -- pointer version
	
		int i = 0;          // i counts number of characters copied
		char * cpys1 = s1;  // make copy of s1 pointer to return

		// copies from s1 into s2 and checks for n limit
		while( i++ < n && (*s1++ = *s2++) ) ;

		// fill empty space with '\0'
		for(; i < n; s1++, i++) {
			*s1 = '\0';
		}

		return cpys1;
	}

