有必要用'\\ 0'memset的,一个玩具的例子 [英] The necessity to memset with '\0', in a toy example

查看:426
本文介绍了有必要用'\\ 0'memset的,一个玩具的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了用memset的下面的例子 tutorialspoint :(我不熟悉用C)

I encountered the following example of using memset in tutorialspoint: (I am not familiar with C.)

#include <stdio.h>
#include <string.h>

int main(){
    char src[40];
    char dest[100];

    memset(dest, '\0', sizeof(dest));
    strcpy(src, "This is tutorialspoint.com");
    strcpy(dest, src);

    printf("Final copied string : %s\n", dest);

    return(0);
}

我不明白为什么使用memset的线,因为编译和结果都是一样的,当该行被注释。我想问一下是必要的行?或者是一个很好的做法,这样做的时候的strcpy()?或者它只是一个随机行。

I don't get why the memset line is used, as the compile and result are the same when that line is commented. I would like to ask is that line necessary? or is it a good practice to do so when doing strcpy()? or it is just one random line.

谢谢!

推荐答案

它不需要在此情况下,在这个意义上,它具有对输出没有影响。它可能需要一些类似的案件。

It's not needed in this case, in the sense that it has no effect on the output. It might be needed in some similar cases.

char dest[100];

这个定义 DEST 为100 字符个本地阵列。它的初始值是垃圾。它的可能的已经被写为:

This defines dest as a local array of 100 chars. Its initial value is garbage. It could have been written as:

char dest[100] = "";

char dest[100] = { 0 };

但这些都不是必要的,因为 DEST 的使用之前被分配一个值。

but none of those are necessary because dest is assigned a value before it's used.

strcpy(src, "This is tutorialspoint.com");
strcpy(dest, src);

此副本包含在中的字符串src 入阵 DEST 。它复制的26个字符这是tutorialspoint.com加1附加字符,终止'\\ 0; 该标记字符串的结尾。在 DEST 数组的previous内容被忽略。 (如果我们使用的strcat(),那就无所谓,因为的strcat()必须找到一个'\\ 0'中,才可以开始复制目标。)

This copies the string contained in src into the array dest. It copies the 26 characters of "This is tutorialspoint.com" plus 1 additional character, the terminating '\0; that marks the end of the string. The previous contents of the dest array are ignored. (If we were using strcat(), it would matter, because strcat() has to find a '\0' in the destination before it can start copying.)

如果没有 memset的()电话,剩下的73个字节 DEST 将是垃圾 - 但止跌T无所谓,因为我们从来不看任何东西过去'\\ 0' DEST [26]

Without the memset() call, the remaining 73 bytes of dest would be garbage -- but that wouldn't matter, because we never look at anything past the '\0' at dest[26].

如果由于某种原因,我们决定将是这样的:

If, for some reason, we decided to add something like:

printf("dest[99] = '%c'\n", dest[99]);

该方案,那么 memset的()会事宜。但是,由于目的 DEST 是召开的字符串的(这是由'\\ 0'<终止定义/ code>空字符),那会不会是做一个明智的做法。完全合法的,但不是明智的。

to the program, then the memset() would matter. But since the purpose of dest is to hold a string (which is by definition terminated by a '\0' null character), that wouldn't be a sensible thing to do. Perfectly legal, but not sensible.

这篇关于有必要用'\\ 0'memset的,一个玩具的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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