带C的数组-这些数字是什么?
我用C语言创建了这个小软件:带C的数组-这些数字是什么?,c,arrays,C,Arrays,我用C语言创建了这个小软件: #include <stdio.h> #include <stdlib.h> void print_this_list(int size){ int list[size]; for (int i = 0; i < size; i++) { printf("%d\n", list[i]); } } int main(int argc, char *argv[]){ print_this
#include <stdio.h>
#include <stdlib.h>
void print_this_list(int size){
int list[size];
for (int i = 0; i < size; i++) {
printf("%d\n", list[i]);
}
}
int main(int argc, char *argv[]){
print_this_list(25);
return 0;
}
这些数字到底是什么?它们背后的“逻辑”是什么?它们背后没有逻辑。这是未定义的行为
void print_this_list(int size){
int list[size]; // not initialized
for (int i = 0; i < size; i++) {
printf("%d\n", list[i]); // still you access it and print it
}
}
这是垃圾。未初始化值 如果你尝试
int x; // i define x as uninitialized variable some where in the memory (non empty)
printf("%d",x); // will print trash "unexpected value
// if i do this
int x=10;//i define x with initial value so i write over the trash was found in this block of the memory .
如果我将超出范围的索引打印为
int ar[10];
for(int i=0;i<10;i++)
ar[i]=rand();
printf("%d\n",ar[10]);//out of index uninitialized index it will print trash .
intar[10];
对于(int i=0;igarbage值,它可以是任何内容!!未定义的行为!!准确地说,它是不确定的,标准将其定义为未指定(即有效但任意的值)或者是陷阱。与UB相反,UB原则上可能意味着任何事情,包括随机值或剥离整个函数的优化器,甚至是严重的不良行为。根据标准的措辞,可能发生的最糟糕的事情是陷阱(即程序终止)@Damon读取陷阱会导致UB,因此使用不确定的原因UB,除非你能证明系统上没有陷阱。@M.M:C标准确实没有定义陷阱,但它们定义得很好。如果安装了处理程序(如果可以安装,但我知道没有操作系统不能安装),则会调用处理程序,否则进程将立即终止。因此,它实际上可以归结为硬件是否能够将某些值标记为无效(如安腾上的NaTVal)或者没有,在这种情况下,你会有陷阱,否则你就不会有陷阱。但在任何情况下,你都不会有未定义的行为。发生的事情总是定义明确的。所有这些都不在C标准中。就C而言,这是UB。实现可能实现UB,但他们选择它不是未定义的行为!不是这个时间!未初始化变量的值是不确定的,可能是陷阱表示,但访问它时不会出现未定义的行为。@FUZxxl您能指出标准中我可以找到更多关于它的信息吗?这是未定义的行为。即使没有陷阱,也会将不确定的值传递给库函数(哪个printf
is)导致未定义的行为。对于discussion@M.M表示我一开始是正确的。这让我很困惑。我不知道陷阱。感谢您的澄清。@FUZxxl读取陷阱会导致UB,即使没有陷阱表示,读取不确定值时也可能有UB(见我之前评论中的链接)
int x; // i define x as uninitialized variable some where in the memory (non empty)
printf("%d",x); // will print trash "unexpected value
// if i do this
int x=10;//i define x with initial value so i write over the trash was found in this block of the memory .
int ar[10];
for(int i=0;i<10;i++)
ar[i]=rand();
printf("%d\n",ar[10]);//out of index uninitialized index it will print trash .