2015-09-27 31 views
0

我创建了C这个小软件:使用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_list(25); 
    return 0; 

} 

执行的结果非常有趣(显然)随机数:

-1519340623 
859152199 
-1231562870 
-1980115833 
-1061748797 
1291895270 
1606416552 
32767 
15 
0 
1 
0 
104 
1 
1606578608 
32767 
1606416304 
32767 
1606423158 
32767 
1606416336 
32767 
1606416336 
32767 
1 
Program ended with exit code: 0 

究竟那些是什么数字,什么是“逻辑“在他们后面?

+4

垃圾值,它可以是任何东西! **未定义的行为**! –

+1

确切地说,它是**不确定**,标准定义为未指定(即有效但任意值)或陷阱。与UB相反,UB原则上可能意味着任何事情,包括随机值或优化器剥离整个函数,甚至是严重不良的行为。根据标准的措辞可能发生的最糟糕的事情是陷阱(即程序终止)。 – Damon

+0

@Damon读取陷阱会导致UB,因此使用不确定性会导致UB,除非您可以证明系统上没有陷阱。 [更详细的答案](http://stackoverflow.com/a/25074258/1505939) –

回答

9

他们背后没有逻辑。它的未定义行为

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 
    } 
} 

list是未初始化的并且打印它的内容(这是不确定的)。因此,你会得到一些随机的垃圾值作为输出。

为了得到工作,你需要初始化它。你可以试试这个 -

void print_this_list(int size){ 
    int list[size];    
    for (int i = 0; i < size; i++) { 
    list[i]=i;     // storing value of i in it before printing   
    printf("%d\n", list[i]);    
    } 
    } 
+0

这不是*未定义的行为!*暂时没有!未初始化的变量的值是* indeterminate *,并且可能是一个陷阱表示,但在访问它时不会发生未定义的行为。 – fuz

+0

@FUZxxl请问您可以在标准的位置找到更多关于它的地方吗? – ameyCU

+0

这是未定义的行为。即使没有陷阱,将不确定值传递给库函数(printf是)会导致未定义的行为。 [见这里](http://stackoverflow.com/questions/25074180/is-aa-or-aa-undefined-behaviour-if-a-is-not-initialized/25074276#25074276)供讨论 –

0

这是垃圾。未初始化值

如果您尝试

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 . 

我希望这有助于

相关问题