2017-05-31 22 views
2

当我多次运行时,以下代码的输出未定义。我想知道为什么输出未定义,以及当我尝试为未知边界数组赋值时会有什么含义。C编程中未知绑定用法的数组

#include <stdio.h> 

int main() 
{ 
    int a[]= {}; 
    int num_of_elements; 
    int count = 0; 

    printf("Enter the number of elements:\n"); 
    scanf("%d",&num_of_elements); 

    printf("Enter the numbers:\n"); 
    for(count=0; count<num_of_elements; ++count) 
    { 
    scanf("%d", &a[count]); 
    } 
    printf("\n"); 

    for(count=0; count<num_of_elements; count++) 
    { 
    printf("%d, ", a[count]); 
    } 
    printf("\n"); 

    return 0; 
} 

输出时在不同的时间运行:

Enter the number of elements: 
2 

Enter the numbers: 
1 2 

0, 0, 

Enter the number of elements: 
3 

Enter the numbers: 
1 2 3 

0, 0, 2, 

Enter the number of elements: 
4 

Enter the numbers: 
1 2 3 4 

0, 0, 2, 3, 
Segmentation fault 

Enter the number of elements: 
5 

Enter the numbers: 
1 2 3 4 5 

0, 0, 2, 3, 4, 
Segmentation fault 
+1

'的INT A [] = {};'是没有用的 - 你必须在*知道它的大小后定义数组*。 –

+0

https://stackoverflow.com/questions/1677157/can-size-of-array-be-determined-at-run-time-in-c – rsp

+1

发布的代码不能编译!它会导致编译器输出两条消息:1)'5:12:警告:ISO C禁止空初始化括号[-Wpedantic]'和2)'5:7:错误:零或负大小数组'a''编译时始终启用警告。然后修复这些警告。 (对于'gcc',最低限度使用:'-Wall -Wextra -pedantic') – user3629249

回答

1

I would like to know why the output is undefined and what will be implication when I try to assign value to an array of unknown bound

变量a的大小将0,为num_of_elements一直没有在这一点上scanf“版,所以你不能存储任何东西。

解决的方法是在之后声明数组您已经从用户读取其大小。这意味着:

#include <stdio.h> 

int main() 
{ 
    int num_of_elements; 
    int count = 0; 

    printf("Enter the number of elements:\n"); 
    scanf("%d", &num_of_elements); 

    //define here your array 
    int a[num_of_elements]; 

    ... 

    return 0; 
} 
+0

仅当__STDC_NO_VLA__是*不被定义为宏标识符时。 – DeiDei

+0

@DeiDei OP在他的程序中没有提到这样一个宏定义......这就是为什么我没有提到这一点。 – Marievi

+0

嗨Marievi等人...感谢您的投入。现在清楚了,并且感谢你介绍了C11标准,它给了我一些洞察, – Vasanth

1

作为第一个提示,当您尝试使用-pedanticgcc编译这一点,就会拒绝编译:

$ gcc -std=c11 -Wall -Wextra -pedantic -ocrap.exe crap.c 
crap.c: In function 'main': 
crap.c:5:12: warning: ISO C forbids empty initializer braces [-Wpedantic] 
    int a[]= {}; 
      ^
crap.c:5:7: error: zero or negative size array 'a' 
    int a[]= {}; 
    ^

事实上,这样一个变量的大小是0 ,所以你不能在其中存储任何东西

尽管如此它是一个有效的语法和有其用途,例如作为一个结构的一个 “可变数组成员”:

struct foo 
{ 
    int bar; 
    int baz[]; 
}; 

[...] 

struct foo *myfoo = malloc(sizeof(struct foo) + 5 * sizeof(int)); 
// myfoo->baz can now hold 5 integers