Section 1.9 of “The
C Programming Language” by Brian
Kernighan and Dennis Ritchie aka K&R
discusses character arrays and how to use them as an argument for a function. The
general rule is that a function receives its argument as a value and not a
reference to a variable. That means the called function can manipulate the
argument without affecting the variable in the calling function. That’s not the
case with a character array. The function can change the array even though the
variable is declared in the calling function. Note: there are excepts for variables
declared outside of a function (i.e., global scope) and where pointers are
used.
The sample code in section 1.9 inputs characters from the
keyboard one line at a time and finds the longest line from all entered.
Two lines of code of interest.
for (i=0; i < lim-1
&& (c=getchar())!=EOF && c!='\n';
++i)
The loop will continue provided three conditions are true:
1. The current character count (i) is less than the limit
less 1,
2. The current character is not EOF, AND
3. The current character is not a newline.
The first condition is required because of the maximum number of
elements the array can hold. Without it, you could exceed the limit and write
data to memory that is being used elsewhere. This leads to corrupted data and
crashed programs.
while ((to[i] = from[i])
!= '\0')
C results in code you wouldn’t expect but work. A single
equal sign is the assignment operator and not the equal to test. The condition
is true until it reaches the end of the array as marked with the null
character.
Sample Code.
I am using Visual C++ 2010 and created the sample code as a
console application.
//
Function prototype.
int getline(char line[], int
maxline);
void copy(char to[], char
from[]);
// The
standard library includes the system function.
#include <cstdlib>
//
Standard I/O library.
#include <cstdio>
#define MAXLINE 1000 /* maximum input line length */
int main()
{
int len; /* current line length */
int max; /* maximum length seen so far */
char
line[MAXLINE]; /* current input line */
char
longest[MAXLINE]; /* longest line saved here */
max = 0;
while ((len
= getline(line, MAXLINE)) > 0)
if
(len > max) {
max = len;
copy(longest, line);
}
if (max
> 0) /* there was a line */
printf("%s",
longest);
// Keep console
window open.
system("pause");
// Return some
value.
return 0;
} // end main
/*
getline: read a line into s, return length */
int getline(char s[],int lim)
{
int c, i;
for (i=0; i
< lim-1 && (c=getchar())!=EOF && c!='\n';
++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* copy:
copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char
from[])
{
int i;
i = 0;
while
((to[i] = from[i]) != '\0')
++i;
}
Output.
The longest line is…
No comments:
Post a Comment