We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
有文件 test.c
test.c
#include <stdio.h> #include <string.h> int main() { int m[2]; printf( "sizeof(m): %lu\n", sizeof(m) ); memset( m, -1, sizeof(m) ); printf( "after memset(m, -1, sizeof(m)): %20d (0x%08x), %20d (0x%08x)\n", m[0], m[0], m[1], m[1] ); memset( m, 1, sizeof(m) ); printf( "after memset(m, 1, sizeof(m)): %20d (0x%08x), %20d (0x%08x)\n", m[0], m[0], m[1], m[1] ); memset( m, 0xFF, sizeof(m) ); printf( "after memset(m, 0xFF, sizeof(m)): %20d (0x%08x), %20d (0x%08x)\n", m[0], m[0], m[1], m[1] ); memset( m, 0xA5, sizeof(m) ); printf( "after memset(m, 0xA5, sizeof(m)): %20d (0x%08x), %20d (0x%08x)\n", m[0], m[0], m[1], m[1] ); }
编译运行
$ gcc test.c -o test $ ./test sizeof(m): 8 after memset(m, -1, sizeof(m)): -1 (0xffffffff), -1 (0xffffffff) after memset(m, 1, sizeof(m)): 16843009 (0x01010101), 16843009 (0x01010101) after memset(m, 0xFF, sizeof(m)): -1 (0xffffffff), -1 (0xffffffff) after memset(m, 0xA5, sizeof(m)): -1515870811 (0xa5a5a5a5), -1515870811 (0xa5a5a5a5)
所以,要小心了。别人用 memset(buf, -1, sizeof(buf)) 来初始化 buf,你用 -2 可不是 -2 啊!
memset(buf, -1, sizeof(buf))
这涉及到 two's compliment 编码。
另一个不符合直觉的是 int buf[50] = { 0 }; 确实会把所有元素初始化为 0,但是 int buf[50] = { 3 }; 只回初始化第一个元素为 3,其它都是 0……至少在我的 gcc 和 g++ 上都是如此。
int buf[50] = { 0 };
int buf[50] = { 3 };
gcc
g++
The text was updated successfully, but these errors were encountered:
No branches or pull requests
有文件
test.c
编译运行
$ gcc test.c -o test $ ./test sizeof(m): 8 after memset(m, -1, sizeof(m)): -1 (0xffffffff), -1 (0xffffffff) after memset(m, 1, sizeof(m)): 16843009 (0x01010101), 16843009 (0x01010101) after memset(m, 0xFF, sizeof(m)): -1 (0xffffffff), -1 (0xffffffff) after memset(m, 0xA5, sizeof(m)): -1515870811 (0xa5a5a5a5), -1515870811 (0xa5a5a5a5)
所以,要小心了。别人用
memset(buf, -1, sizeof(buf))
来初始化 buf,你用 -2 可不是 -2 啊!这涉及到 two's compliment 编码。
另一个不符合直觉的是
int buf[50] = { 0 };
确实会把所有元素初始化为 0,但是int buf[50] = { 3 };
只回初始化第一个元素为 3,其它都是 0……至少在我的gcc
和g++
上都是如此。The text was updated successfully, but these errors were encountered: