我试图从结构中的指针数组中获取元素。不确定我是否正确地做到了这一点。
#include<stdio.h>
typedef struct _str
{
int *a;
} _str;
main()
{
_str s[]={
{1000,2000},
{3000,4000,5000}
};
printf("%d\n", s[0].a);
printf("%d\n", s[0].a + 1); /* Gives me 1004 instead of 2000 */
printf("%d\n", s[1].a);
printf("%d\n", s[1].a + 1); /* Gives me 3004 instead of 4000 */
}
答案 0 :(得分:2)
代码编写不干净:
$ gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition wd.c -o wd
wd.c:9:5: warning: return type defaults to ‘int’ [enabled by default]
wd.c:9:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
wd.c: In function ‘main’:
wd.c:9:5: warning: old-style function definition [-Wold-style-definition]
wd.c:12:13: warning: initialization makes pointer from integer without a cast [enabled by default]
wd.c:12:13: warning: (near initialization for ‘s[0].a’) [enabled by default]
wd.c:12:13: warning: excess elements in struct initializer [enabled by default]
wd.c:12:13: warning: (near initialization for ‘s[0]’) [enabled by default]
wd.c:13:13: warning: initialization makes pointer from integer without a cast [enabled by default]
wd.c:13:13: warning: (near initialization for ‘s[1].a’) [enabled by default]
wd.c:13:13: warning: excess elements in struct initializer [enabled by default]
wd.c:13:13: warning: (near initialization for ‘s[1]’) [enabled by default]
wd.c:13:13: warning: excess elements in struct initializer [enabled by default]
wd.c:13:13: warning: (near initialization for ‘s[1]’) [enabled by default]
wd.c:16:9: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]
wd.c:17:9: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]
wd.c:19:9: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]
wd.c:20:9: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]
$
基本上,这就是说“你不能这样做”,至少,不是那样。
警告并不意味着你无法做某事。
在你能够忽略编译器发出的警告之前,你必须对C做得好,不要问这类问题。一般来说,编译器(或者至少是编译器) 编译器)比你更了解C语言。直到你知道足够能够引用标准的章节和经文来解释为什么不应该给出警告,将编译器的单词视为福音。如果我正在审查你的代码,千万不要试图偷偷摸摸那些过去的代码 - 我不会接受它。
可以使用C99复合文字拯救代码:
#include <stdio.h>
typedef struct str
{
int *a;
} str;
int main(void)
{
str s[] =
{
{ (int[]){1000,2000} },
{ (int[]){3000,4000,5000} },
};
printf("%d\n", *(s[0].a + 0));
printf("%d\n", *(s[0].a + 1));
printf("%d\n", s[1].a[0]);
printf("%d\n", s[1].a[1]);
}
此外,以下划线开头的名称基本上是为实现保留的。这些规则稍微有些细微差别,但为了最大限度地提高安全性,您不会创建以下划线开头的名称。因此,我将_str
重命名为str
,但str
更常用于表示'字符串'而不是C中的'struct'(但我的想法用完了更好的名字)。注意printf()
语句中所需的额外间接级别,在前两个中写入一个,在后两个中写入另一个。