被初中生 C 语言考住了,尴了个尬

2022-08-28 11:32:15 +08:00
 52coder

周末来老婆老家,她亲戚有个小孩读初中,有个兴趣班学的 C 语言,得知我是从事软件开发 5 6 年的“高手”,饭后问了我一道编程题,我三俩下就告诉他怎么 怎么写,结果提交的时候始终显示有问题,一排查发现这里有坑,我手写一个 demo (可能编译不过哈)请教各位如下程序输出是什么?

#include <stdio.h>
int main()
{
    int arr[10] = {-1};
    //打印 arr 全部内容
    for(int i = 0;i < 10;i++)
    printf("%d",arr[i]);
    
    return 0;
}

我之前一直以为会全部输出-1 ,结果在 gcc 11.2.0 的环境下,输出确实一个-1 ,然后全是 0.有没有踩过这个坑的朋友?

10181 次点击
所在节点    程序员
83 条回复
jiulang
2022-08-30 11:00:06 +08:00
如果语言上没有明确的标准定义,而是靠编译器看着办,那应该在代码上抛弃语言的这个特征
autumn426
2022-08-30 11:10:35 +08:00
不写是随机 写了编译器会自己把后面的补 0
metalbuild
2022-08-30 14:23:41 +08:00
记忆中 The C Programming Language (2nd Edition) by Brian W. Kernighan, Dennis M. Ritchie 这本书有详细说明 我特意翻查了一下 section 4.9 initialization 本小白只是个半途自学的 有错请指出

An array may be initialized by following its declaration with a list of initializers enclosed in braces and separated by commas. For example, to initialize an array days with the number of days in each month:

int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

When the size of the array is omitted, the compiler will compute the length by counting the initializers, of which there are 12 in this case.

>> If there are fewer initializers for an array than the number specified, the missing elements will be zero for extemal, static, and automatic variables. It is an error to have too many initializers. There is no way to specify repetition of an initializer, nor to initialize an element in the middle of an array without supplying all the preceding values as well. <<

Character arrays are a special case of initialization; a string may be used instead of the braces and commas notation:
char pattern [] = "ould";
is a shorthand for the longer but equivalent
char pattern[] = { 'o', 'u', '1', 'd', '\0' };
In this case, the array size is five (four characters plus the terminating ' \0').

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/875942

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX