如何阅读本C数组声明/初始化? [英] How to read this C Array declaration/initialization?

查看:124
本文介绍了如何阅读本C数组声明/初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char *names[] = {
        [3] = "foo", 
        [1] = "bar", 
        [0] = "man"};

int i;
for (i=0; i<sizeof(names)/sizeof(char); i++)
{
    puts(names[i]);
}

什么是在上面的声明中括号的功能?此外,为什么生成的循环迭代,而不是4 3次,产生这种输出:

What are the function of the brackets in the above declaration? Also, why does the resulting loop iterate 3 times instead of 4 and produce this output:

推荐答案

在括号中的数字是初始化的指数。这是C99的功能。

The numbers in brackets are the indices of the initializers. This is a C99 feature.

由于您的例子code不使用这个缺陷,您会收到你做输出的原因是,foo被保存在名称[3] ,而 NULL 存储在名称[2] 。当它试图使你的程序崩溃(名称[2])这是一样的看跌期权(NULL)

Given that your example code does use this blemish, the reason you receive the output you do is that "foo" is stored in names[3], while NULL is stored in names[2]. Your program crashes when it attempts to puts(names[2]) which is the same as puts(NULL).

您循环,否则重复16或32次 - 你被划分的sizeof(char)的的数组元素的大小,你的意思是使用的sizeof(字符*)

Your loop would otherwise iterate to 16 or 32 iterations -- you are dividing by sizeof(char) for the array element size, and you mean to use sizeof(char *).

更好的使用这个宏:

#define DIMENSION_OF (a) (sizeof(a)/sizeof(a[0]))

我从来不建议使用任何特定的C99的功能,如这些指定初始化。

I suggest never using any C99-specific features, such as these "designated initializers."

有一个原因,最让你在这个问题上收到的答案感到困惑,为什么你的循环只能输出,而两个字符串超过四个。这原因是C99并未广泛被其他程序员的认可。

There is a reason that most of the answers you received on this question were confused as to why your loop only output two strings rather than four. That reason is that C99 is not widely recognized by other programmers.

有几个原因,大多数程序员不熟悉C99的更鲜明的特点。一个经常提到的原因是,C99是C ++比ANSI C的不兼容,使未来转换成C ++更困难的可能性。我个人的投诉C99也使得扩展ANSI C这是多余的。一个多余的加成的一个例子是已提供从C99的例子。不要使用指定inits。请参阅美国国家标准学会C标准。不要指国际标准化组织的C99文件。

There are several reasons that most programmers aren't familiar with C99's more distinctive features. A frequently cited reason is that C99 is more incompatible with C++ than ANSI C, and makes the possibility of future conversion to C++ more difficult. My personal complaint with C99 also makes extensions to ANSI C which are superfluous. An example of a superfluous addition is the example from C99 that you have provided. Don't use "designated inits." Do refer to the American National Standards Institute C Standard. Do not refer to the International Standards Organization C99 document.

大多数这是最好有特点的形式C99已经可以作为在所有主要的编译器扩展。在换初始化语句声明一个变量是一种被广泛支持的非ANSI-C标准的特性的一个例子。在复杂内置型是一种非ANSI-C标准的功能未得到广泛支持的一个例子。

Most of the features which are "nice to have" form C99 were already available as extensions in all major compilers. Declaring a variable in the for-init-statement is an example of a non-ANSI-C-standard feature which is widely supported. The complex built-in type is an example of a non-ANSI-C-standard feature that is not widely supported.

这篇关于如何阅读本C数组声明/初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆