Reputation: 73
I am fairly new to C, and I am working through Ritchie's and Kernighan's The C programming language, and I don't understand how the following code works:
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
int main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while((len = getline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0)
printf("%s", longest);
return(0);
}
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;
}
s[i] = '\0';
return(i);
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
What I don't get is how does the copy function affect anything without returning anything, I am used to Python where functions can only affect outwith themselves through return values, and I was under the impression C was the same. I have tested the code and it does work.
Upvotes: 1
Views: 134
Reputation: 401
void copy(char to[], char from[])
is actually the same like void copy(char *to, char *from)
. So, two pointers are passed to the copy function. The function can change the destinations of the pointers. This mechanism is known as "call by reference".
(The copy function only needs to change the destination of the to-pointer, the destination of the from-pointer needs not to be changed. This can be made clearer with void copy(char *to, const char *from)
.)
Upvotes: 0
Reputation:
That copy
function works through the magic of pointers.
In essence, pointers are basically a memory address that you can access like an array from the same program.
On a side note, Learn C the Hard way is, in my opinion, a better book.
He explains many concepts of C, and he also points out some flaws in that very same .copy
function you are asking about
UPDATE
He actually removed his section on K&R C, because he believes that C is dead. I think he is wrong, but, to each his own.
Upvotes: 2
Reputation: 46331
The statement while ((to[i] = from[i]) != '\0')
is actually an assignment disguised within the comparison.
It's a shorthand code that I personally find confusing, and you're proving that it infact is.
Upvotes: 4