K & R What does a char reset array look like?

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  /* 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 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?

+4
source share
2 answers

How is the old entrance erased? Am I referring to the same array that previously stored the previous input?

. input (s[i] = '\0';) getLength() .

, ( ). , "".

+5

C . char input[MAXLINE]; 1000 . , . , , - .

char '\ 0'. , - stdio.h, , , . , , strlen stdio.h, . .

0

Source: https://habr.com/ru/post/1653051/


All Articles