Hi everyone, I'm beginning to learn about progamming and I'm currently working through the seminal 'C Programming Language' which is excellent, but I have a problem regarding functions.
My understanding of functions in C is that they return a value. For example:
x = func(a, b);
...would set x to the value returned by 'func'.
But it seems that the variables used within a function are local to that function, and do not alter the variables in the original function that called them.
However the following example seems to show the values of the called function making changes in the calling function's variables, and which are then passed to another function.
main() {
int len, max;
char line[1000];
char longest[1000];
max = 0
while ((len = getline(line, 1000)) > 0)
if (len > max) {
max = len;
copy(longest, line)
}
}
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;
}
void copy(char to[], char from[]) {
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
In other words, 'line' is passed by main to function 'getline' as an empty character array. Getline fills a local array, s, with the characters of the next line and returns the total length of the line to main.
But somehow the character array 'line' has been filled with the contents of the array 's', because line may then be passed to 'copy', which fills another array, to, with its contents.
In contrast in a program such as this:
main() {
int a, b;
a = 1;
b = 2;
c = func(a, b);
printf("%d %d %d", a, b, c);
}
int func(int aa, int bb) {
aa = 4;
bb = 5;
return 0;
}
...will output:
1 2 0
because the variables aa and bb are local to func, and do not affect a and b, their analogues in main.
So, it seems that an array can be passed to a function, and this function may fill the original array by filling its local array.
Is this right? Or is there some property of functions and/or arrays I've failed to understand?
I apologise if there are mistakes in the code or this is an inanely stupid question. If anyone can help me I'll be exceptionally grateful!
Thanks!
Ben