In K & R, we present char arrays to represent strings.
Arrays are passed by reference. As far as I understand, we can point to the first element in the array (pointer?). Using a char array inputwithout specifying its values means that it sets garbage data inside the array. (Honestly, not quite sure what kind of garbage data may have zeros?).
In any case, the empty char array is first passed to the function getLength, and it sets the inputs of the char array. In my code, I show an array lenand char input.
On the next input, I call again getLengthand pass in the same char array input. I set the values as before and return the length.
How is the old entrance erased? Am I referring to the same array that previously stored the previous input? Below my code I will show an example.
#include <stdio.h>
#define MAXLINE 1000
int getLength(char s[]);
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;
}
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 enter "Hello", I do not use the previous array in which "Hello my name is Philip" is stored. Therefore, I do not expect the array to look like this:
['H', 'i', '\n', '\0', 'o', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'P', 'h', 'i', 'l', 'i', 'p', '\n', '\0', etc...]
Edit:
To clarify, I understand how it printf("%s", input)prints the correct line. I also understand that it getLengthwill return the correct length every time.
I just got confused about the characters stored in the array input. If we reference the same array in memory, how are old characters handled?