0

I've just started with C and am following along in "The C Programming Language".

In the first chapter I found something that seems quite strange for me (I've done a lot of work in higher level code like JS, Python, C#). What I'm referring to is this snippet that reads input, analyses its length and then copies it if longer than previous:

#include <stdio.h>

#define MAXLINE 1000

int get_line(char line[], int limit);
void copy(char to[], char from[]);


int main () {

    int len, max;
    char line[MAXLINE], longest[MAXLINE];

    max = 0;

    while((len = get_line(line, MAXLINE)) > 0) { // <-- here
        if (len > max) {
            max = len;
            copy (longest, line);
        }
    }

    if (max > 0) {
        printf("Longest string: %sLength: %d\n", longest, max);
    }

    return 0;
}

int get_line(char line[], int limit) {

    int current, index;

    for (index = 0; index < limit -1 && (current = getchar()) != EOF && current != '\n'; ++index)
        line[index] = current;

    if (current == '\n') {
        line[index] = current;
        ++index;
    }
    line[index] = '\0';
    return index;
}

void copy (char to[], char from[]) {

    int index = 0;

    while ((to[index] = from[index]) != '\0')
        ++index;
}

The strange thing in this snippet is how the parameters in the function calls to get_line and copy seem to be references (even though they aren't pointers?).

How for instance is line and longest values the same in main as in the helper functions even though main is missing any scanner and none of the helper functions returns the character arrays.

geostocker
  • 1,190
  • 2
  • 17
  • 29
  • Array name stores base address of that array, which means you are passing address. – Sniper Apr 23 '17 at 19:29
  • Ah, cheers! Makes a lot more sense now! :) – geostocker Apr 23 '17 at 19:29
  • @Sniper "Array name stores base address" is not quite right... the compiler knows where the array should be much like it knows where a plain `int` should be, but the array doesn't hold the address of its elements. In most situations where you use the array name, you get a pointer to the first element instead -- but it's not stored in the array (kind of like how using `&` with an `int` gives you a pointer to the `int` even though the `int` variable doesn't store that address). – Dmitri Apr 23 '17 at 19:51

0 Answers0