我最近发现在我的代码中使用array_search函数时遇到了麻烦.我正在搜索数组"$ allcraftatts"的值为"sharp".我尝试通过设置两行实验来解决问题:
$testcopy=$allcraftatts;
$testsharp=array_search("sharp", $testcopy);
Run Code Online (Sandbox Code Playgroud)
使用"print_r(get_defined_vars());" 后来,我得到了这个结果:
[testcopy] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => Sharp Stone
[7] => Sharp Stones
[8] => stone
[9] => object
[10] => sharp
[11] => hard
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 0
[18] => 0
)
[testsharp] => 0
Run Code Online (Sandbox Code Playgroud)
我确保在任何其他时间都不修改这些变量.
现在,如果我将代码更改为
$testcopy=$allcraftatts;
unset($testcopy[0]);
$testsharp=array_search("sharp", $testcopy); …Run Code Online (Sandbox Code Playgroud) 编辑:我所说的“有效类型”在C11 Standard - \xc2\xa76.5 Expressions (p6,7)中提到。(感谢 David C. Rankin 在评论中提供此链接。)
\n\n经过一些阅读后,我并不完全理解 C 中关于有效类型和严格别名的规则。我在下面的代码中评论了我认为有效类型所发生的情况。在本示例中,请假设 int 和 float 大小相同。
\n\nvoid *memory = malloc(sizeof(int) + sizeof(float));\n\nint *x = memory; // x points to an "object" with no effective type.\n*x = 1; // x points to an object with effective type int.\nfloat *y = memory; // y points to an object with effective type int.\n++y; // y points to an "object" with effective type ???\nRun Code Online (Sandbox Code Playgroud)\n\n最后,y指向尚未写入的内存。因此,如果 y 指向一个没有有效类型的“对象”,这对我来说是有意义的。
\n\n …