Originally Posted by
rllovera
Hi, all. I'm writing because there's something I don't understand in K&R's book. In Section 1.9 (character arrays), an example code is given in which the main function calls a function named getline. When getline is called for the first time, two arguments are (supposedly) passed to it, a character array named line and an integer named maxline.
Right at this point I get confused. Up to this point in the code, the line array has only been declared but it has not been assigned any value. So, if line has not been assigned any value before calling getline, how does any character array get passed to this last function?
In Section 1.7 (functions), a function named power is called by main. But this time, two previously defined arguments are passed to power. This example I can understand, but the inner working of the example in Section 1.9 is uncomprehensible for me at my current level in C programming.
So, if anyone knows how to give a clear explanation about this subject, I'd love to hear it.
Thanks in advance to those who take the time to read this post.
Roberto.
Code:
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
int main(void)
{
int len;
int max;
char line[MAXLINE]; /* declare array of type char with
MAXLINE (1000) elements */
char longest[MAXLINE];
max = 0;
/* call getline function and pass the address
of the first element of the array (line), and the
size of the array (MAXLINE, or 1000) */
while ((len = getline(line, MAXLINE)) > 0)
.....
What happens is that the function getline() is called, which reads a line into the array that is passed to it. After getline is called, and assuming the user entered some text, the array line has the text stored in it. Then when the last function copy is called, it is passed the array line and another array longest so it can copy the contents of one array into another. If you want to get a little more technical, when getline is called (and keep this in mind for any function which has an array as a parameter) it is actually passed the address of line[0]. In this way, the function can work directly on the array line. In effect, the call to getline is telling the function, 'here is an address of the first element of an array (in this function it is line, which is like saying line[0], for the array name is essentially the same thing as saying array[0]), so that you know where to find the variable in order to work on it (eg., store characters in it), and also here is the size of that array so you don't overstep the bounadaries of that array' (because overstepping the boundaries of an array is a bad thing).
~/