75895

Easy C longest line copying program

Question:

This is variation of one of exercises from Kernighan C book. Basically prints the longest line from standard input.

My question is, if looking at the 'copy method', how does the copy method actually work if it returns void. I'm coming from Java and learning C for the first time. <strong>In the copy method, the to and from char arrays are local. How do they actually get stored in longest and line variables in the main method if they are in no way returned back to main?</strong>

I am very confused...

Thanks very much for the time!

<em>Edit: Thank you for the replies.</em>

One more note...

Oh. So you the author is passing the values with pointers. That is extremely confusing since the a page before it reads - "...in C the called function cannot directly alter a variable in the calling function; it can only alter its private, temporary copy." Is that correct?

Second question is, how can I make these functions pass data around just like in Java, PHP and etc. Or is this something C programmers see as a benefit?

<h3>Code from K&R</h3> #include <stdio.h> #define MAXLINE 1000 int getline(char line[], int maxline); void copy(char to[], char from[]); 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 line[], int limit) { int i, c; for (i = 0; i < limit - 1 && (c = getchar()) != EOF && c != '\n'; i++) line[i] = c; if (c == '\n') { line[i] = c; i++; } line[i] = '\0'; return i; } void copy(char to[], char from[]) { int i; i = 0; while((to[i] = from[i]) != '\0') i++; }

Answer1:

In C, <strong>everything is passed by value</strong>. You have to pay attention <strong>what</strong> is passed by value, though.

A C-style array like char from[] is not a container object, like you might expect from other languages. For most practical purposes, a C array is equivalent to a pointer to the first element, i.e. char * from.

So, the parameters to and from do get passed by value, but what they are is <strong>pointers</strong> to the data, so you can modify the data pointed to through them.

Answer2:

Whereas Java strings are immutable, in C "strings" are merely arrays of characters. By changing the characters inside the array, the changes are 'visible' outside copy().

Answer3:

In an update to the question, you ask:

<blockquote>

"…in C the called function cannot directly alter a variable in the calling function; it can only alter its private, temporary copy." Is that correct?

</blockquote>

Yes, that is correct, even for arrays. The reasoning is subtle, though.

For an integer argument:

int somefunc(int i) { return ++i; }

the change to i in the function only affects the copy of i, not the value corresponding to i in the calling function:

int i0 = 26; int i1 = somefunc(i0);

Similarly, for an 'array' argument:

int anotherfunc(int a[]) { return *++a; }

and call:

int array[3] = { 13, 23, 37 }; int n = anotherfunc(array);

the function receives a copy of the pointer array (aka &array[0]), and the change that the function makes to a in the function has no effect whatsoever on array in the calling code. However, if the function is:

int modifyfunc(int a[]) { return *(++a) = 37; }

with the call sequence:

int array[3] = { 13, 23, 37 }; int n = modifyfunc(array); int *ip = &array[1]; int m = modifyfunc(ip);

then the function does not modify the value of array — a pointer — in the calling function, but it does modify the data that the array points at (to be precise, it sets array[1] to 37 for the first call, and array[2] to 37 for the second call), as well as modifying the copy of array (known as a inside the function).

So, as stated, C only has pass by value, but when the value passed is a pointer, it is possible for the called code to modify what the pointer points at — but not the actual pointer in the calling code.

<sub><em>Yes, the side-effects in the functions shown are always unnecessary. They illustrate the point, rather than being realistic code.</em></sub>

Answer4:

First of all, this is horrible code that you are learning from. It is hard to read, hard to understand, and doesn't handle lines longer than a given limit. Ick.

But to answer your question, when copy() is called, the two arguments are pointers to the regions in memory where the character arrays are stored. So when copy is called, the variable "to" equals "longest" in the calling frame, and "from" equals "line" in the calling frame.

Recommend

  • Pure black background in PyCharm CE and Android Studio
  • Use of multiple threads in a Java program and vs need to create Swing objects on EDT
  • Does the program counter always have to change (upon a clock tick)?
  • Client-side prediction & server reconciliation
  • file read() const correctness
  • Is an if-let or a normal if condition better?
  • MySql - get days remaining
  • NSMutableArray Access Issue
  • Converting simple MySQL database to a NoSQL solution
  • Reassigning an array frees the memory used by it?
  • Neo4j: Legacy Indexes and auto index vs new label bases schema indexes
  • Converter from SAT to 3-SAT
  • What does “t” refer to in this SQL?
  • JSR-330 support in Picocontainer : @Inject … @Named(\"xxx)
  • CERN ROOT exporting data to plain text
  • Creating a DropDownList
  • Who propagate bugfixes across branches (corporate development)?
  • Web.config system.webserver errors
  • Scrapy recursive link crawler
  • Fetching methods from BroadcastReceiver to update UI
  • output of program is not same as passed argument
  • Does CUDA 5 support STL or THRUST inside the device code?
  • Javascript + PHP Encryption with pidCrypt
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Upload files with Ajax and Jquery
  • Do I've to free mysql result after storing it?
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • Why winpcap requires both .lib and .dll to run?
  • 0x202A in filename: Why?
  • A cron job substitute?
  • json Serialization in asp
  • Getting Messege Twice Using IMvxMessenger
  • embed rChart in Markdown
  • File not found error Google Drive API
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • Reading document lines to the user (python)
  • How can i traverse a binary tree from right to left in java?
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app
  • How can I use threading to 'tick' a timer to be accessed by other threads?