我正在尝试从结构中的指针数组中获取元素。不确定我是否以正确的方式进行操作。
#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 */
}
最佳答案
代码编译不干净:
$ 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]
$
基本上,这就是说“你不能那样做”,至少不是那样。
A warning doesn't mean you can't do something.
您必须精通 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 中更常用于表示“string”而不是“struct”(但我运行没有更好的名字的想法)。请注意 printf()
语句中需要的额外间接级别,在前两个语句中以一种方式编写,在后两个语句中以另一种方式编写。
关于c - 使用指针获取结构中动态int数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16746075/