为什么我们需要在C语言的字符数组的末尾添加'\ 0'(空)? [英] Why do we need to add a '\0' (null) at the end of a character array in C?

查看:157
本文介绍了为什么我们需要在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 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] = '\0'; //WHY DO WE DO THIS???
    return i;
}

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

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

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

推荐答案

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

You need to end C strings with '\0' 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).

这篇关于为什么我们需要在C语言的字符数组的末尾添加'\ 0'(空)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆