gpt4 book ai didi

c - memset(&mystruct, 0, sizeof mystruct) 和 mystruct = { 0 }; 一样吗?

转载 作者:太空狗 更新时间:2023-10-29 16:28:17 25 4
gpt4 key购买 nike

我正在阅读有关数组/结构默认初始化值的内容,并有以下问题:

memset(&mystruct, 0, sizeof mystruct) 是否与 mystruct = { 0 }; 相同?

如果不是,有什么区别?

最佳答案

is memset(&mystruct, 0, sizeof mystruct) same as mystruct = { 0 }; ?

没有。

memset(&mystruct, 0, sizeof mystruct) ;

... 将告诉编译器调用一个函数,我们希望该函数在执行期间将 mystruct 中的数据设置为零。

mystruct = { 0 };

...将设置告诉编译器自己将数据设置为零,这意味着它将:

  • 如果可能,将 mystruct 中的数据设置为零在编译时(例如,对于静态变量,如注释中的 tristopiaOli Charlesworth 所述)<
  • 如果不是(例如自动变量),生成汇编代码,在初始化变量时将数据设置为零(这比调用函数更好)。

请注意,也许编译器可以将 memset 优化为编译时指令(例如用第二个版本替换第一个版本),但我不会依赖因为 memset 是运行时库中的一个函数,而不是某种语言固有的(虽然我不是编译器编写者/语言律师)。

来自 C++,我自己的观点是,你在编译时可以做的越多,编译器在编译时知道的越多,甚至在执行开始之前,就越好:它使编译器有可能优化代码和/或生成警告/错误。

在当前情况下,使用 mystruct = { 0 }; 符号来初始化 struct 总是比使用 memset 更安全,因为它非常非常 使用 memset 很容易在 C 语言中写错东西,编译器不会报错。

以下示例表明代码很容易做一些与看起来不同的事情:

// only the 1st byte will be set to 0
memset(&mystruct, 0, sizeof(char)) ;

// will probably overrun the data, possibly corrupting
// the data around it, and you hope, crashing the process.
memset(&mystruct, 0, sizeof(myLARGEstruct)) ;

// will NOT set the data to 257. Instead it will truncate the
// integer and set each byte to 1
memset(&mystruct, 257, sizeof(mystruct)) ;

// will set each byte to the value of sizeof(mystruct) modulo 256
memset(&mystruct, sizeof(mystruct), 0) ;

// will work. Always.
mystruct = { 0 } ;

关于c - memset(&mystruct, 0, sizeof mystruct) 和 mystruct = { 0 }; 一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10788861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com