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

查看:23
本文介绍了为什么我们需要在 C 中的字符数组末尾添加一个''(null)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们需要在 C 中的字符数组末尾添加一个 '' (null)?我在 K&R 2 (1.9 Character Array) 中读过它.书中查找最长字符串的代码如下:

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!='
'; ++i)
        s[i] = c;
    if (c == '
') {
        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;
}

我的问题是为什么我们将字符数组的最后一个元素设置为''?没有它,该程序可以正常工作...请帮帮我...

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 字符串,因为这是库知道字符串在哪里结束的方式(并且,在你的情况,这是 copy() 函数所期望的).

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).

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

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