December 1998
CA208: 'C' PROGRAMMING

QUESTION 3

Total Marks: 20 Marks

Click here to access other questions

Click to access
SUGGESTED SOLUTIONS
for Question 3

 

(a) What integer will be returned by the function call strfun1("hello")? Describe the effect of the function when given an arbitrary string as an argument.

int strfunl(char *src) {
   int i;
   for(i=0;*src;(i++,src++)) {}
   return i;
}

 

[3]
(b) Give the function call strfun2(dst,"hello","world"), what string will be copied into dst by the function? Describe the effect of the function on the argument dst, if x and y are null terminated strings, and dst is a sufficiently large character array.

void strfun2(char *dst, char *x, char *y) {
   char *ptr;
   for(ptr=x; *ptr; *dst++=*ptr++) {}
   for(ptr=y; *ptr; *dst++=*ptr++) {}
}

 

[3]
(c) What integer will be returned by the function call strfun3("hello,"hello")? Describe the effect of the function when given an arbitrary string as an argument.

int strfun3(char *x, char *y) {
   int res=0;
   for(;; (x++,y++)) {
      res+=*x - *y;
      if (!*x || !*y) break;
   }
   return res;
}

 

[3]
(d) What integer will be returned by the function call strfun4("hello,"hello")? Describe the effect of the function when given an two arbitrary string as arguments.

int strfun4(char *x, char *y) {
   for(;; (x++,y++)) {
     if (!*x) break;
     if (!*y) break;
     if (*x!=*y) return 0;
   }
   return (*x==*y);
}

 

[3]
(e) What string will be returned by the function call strfun5("hello", 'l')? Describe the effect of the function when given an arbitrary string and character as an arguments.

char *strfun5(char *src, char c) {
   char *ptr;
   for(ptr=src;*ptr;*ptr++)
      if (*ptr==c) break;

   if (!*ptr) return NULL;
   else return ptr;
}
  

 

[3]
(f) Define an implementation of a function strncpy, with function prototype shown below, which copies at most n characters of the string src into dst. You can assume that dst is a character string with at least n+1 elements.

void strncpy(char *dst, char *src, int n);

[5]