为什么我们需要在C语言的字符数组的末尾添加'\ 0'(空)?末尾、数组、字符、语言

由网友(心狠手辣唐老鸭)分享简介:为什么我们需要在C语言的字符数组的末尾添加'\ 0'(空)?R 2(1.9字符数组);我在K&放大器读它。在code在书中找到最长的字符串如下:Why do we need to add a '\0' (null) at the end of a character array in C?I've read it...

为什么我们需要在C语言的字符数组的末尾添加' 0'(空)? R 2(1.9字符数组);我在K&放大器读它。在code在书中找到最长的字符串如下:

Why do we need to add a '' (null) at the end of a character array in C? I've read it in K&R 2 (1.9 Character Array). The code in the book to find the longest string is as follows :

#include <stdio.h>
#define MAXLINE 1000
int readline(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 = readline(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0)
        printf("%s", longest);
    return 0;
}

int readline(char s[],int lim) {
    int c, i;
    for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='n'; ++i)
        s[i] = c;
    if (c == 'n') {
        s[i] = c;
        ++i;
    }
    s[i] = ''; //WHY DO WE DO THIS???
    return i;
}

void copy(char to[], char from[]) {
    int i;
    i = 0;
    while ((to[i] = from[i]) != '')
        ++i;
}

我的问题是,为什么我们设置的字符数组作为' 0'的最后一个元素? 该项目工程优良,没有它... 请帮我...

My Question is why do we set the last element of the character array as ''? The program works fine without it... Please help me...

推荐答案

您需要结束C字符串与' 0',因为这是库如何知道哪里字符串结束(和你的情况,这就是复制()函数需要)。

You need to end C strings with '' since this is how the library knows where the string ends (and, in your case, this is what the copy() function expects).

该程序工作正常,没有它...

The program works fine without it...

如果没有它,你的程序有未定义行为。如果这个程序碰巧你希望它做的事情,你只是幸运(或者说,不吉利,因为在现实世界的不确定的行为会选择体现在最不方便的情况下)。

Without it, your program has undefined behaviour. If the program happens to do what you expect it to do, you are just lucky (or, rather, unlucky since in the real world the undefined behaviour will choose to manifest itself in the most inconvenient circumstances).

阅读全文

相关推荐

最新文章