L-5 MCS 275 Fri 19 Jan 2001
Below are listings for programs we discussed in class.
/* MCS 275 L-5 Fri 19 Jan 2001 : pointers to process strings */
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 80 /* maximum #characters in string */
int read_line (char s[]);
/* Reads a line of characters (until user hits enter).
The string read is in "s" and the function returns the number
"n" of characters in the string, i.e.: s[n] == '\0' */
int ptr_read_line (char *s);
/* This is the equivalent pointer version of the read_line,
with the exception that there are no limits on the length. */
int main()
{
char line[MAXLEN];
char *ptr;
int i,n;
printf("Give a line (< %d characters) : ", MAXLEN);
n = read_line(line);
printf("Your line is :\n \"%s\" \n", line);
printf("There are %d characters on this line.\n", n);
printf("Let us test the pointer version... \n");
printf("Give a line (< %d characters) : ", MAXLEN);
ptr = calloc(MAXLEN,sizeof(char));
n = ptr_read_line(ptr);
printf("Your line is :\n \"%s\" \n", ptr);
printf("There are %d characters on this line.\n", n);
free(ptr);
return 0;
}
int read_line (char s[])
{
int c,i;
for (i=0; (c=getchar()) != EOF && c != '\n' && i < MAXLEN; ++i)
s[i] = c;
s[i] = '\0';
return i;
}
int ptr_read_line (char *s)
{
int c,i;
char *p;
p = s;
for (i=0; (c=getchar()) != EOF && c != '\n' && i < MAXLEN; ++i)
{
*p = c;
++p;
}
*p = '\0';
return i;
}