philip yoo philip yoo - 3 months ago 7
C Question

K&R How is the char array being reset?

In K&R, we are introduced to char arrays to represent strings.

Arrays are passed by reference. From what I understand, we can point to the first element in an array (pointer?). Using the char array

input
without really defining its values means it sets garbage data inside the array. (Honestly not really sure what garbage data is, maybe nulls?).

Anyways, initially the empty char array is passed to function
getLength
, and it sets char array inputs. In my code, I display the
len
and char array
input
.

On the next input, I call
getLength
again, and pass the same char array
input
. I set the values like before and return the length.

How is the old input erased? Aren't I referencing the exact same array that previously stored the previous input? Below my code, I'll show an example.

#include <stdio.h>

#define MAXLINE 1000 /* For allocating storage size for char array */

int getLength(char s[]); /* set char array and return length */

int main(void) {
int len;
char input[MAXLINE];

while ((len = getLength(input)) > 0) {
printf("len = %d\n", len);
printf("string = %s", input);
}
}

int getLength(char s[]) {
int i, c;

for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
s[i] = c;
}

if (c == '\n') {
s[i++] = '\n';
}

s[i] = '\0';

return i; /* return length including newline */
}


Example:

Input: "Hello my name is Philip"
Output: "len = 24"
"string = Hello my name is Philip"

Input: "Hi"
Output: "len = 3"
"string = Hi"


When I input "Hi", aren't I using the previous array that has "Hello my name is Philip" stored inside. So won't I expect the array to look like:

['H', 'i', '\n', '\0', 'o', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'P', 'h', 'i', 'l', 'i', 'p', '\n', '\0', etc...]


Edit:

Just to clarify, I understand how
printf("%s", input)
is printing the correct string. I also understand
getLength
will return the correct length every time.

I'm just confused about the chars saved in the array
input
. If we are referencing this same array in memory, how are old chars being handled?

usr usr
Answer

How is the old input erased? Aren't I referencing the exact same array that previously stored the previous input?

The old input is not erased. In each iteration of the loop, you are just overwriting the same array input and is freshly zero terminated (s[i] = '\0';) by getLength() in each iteration.

Since you are printing the string before the next iteration, it makes it possible to reuse the same array (and overwrite it). So, there really isn't any need to "save" anything.

Comments