在顶层的指针数组c没有大小声明 [英] C array of pointers on top level without size declaration

查看:411
本文介绍了在顶层的指针数组c没有大小声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code编译并产生输出像我期望的那样。

This code compiles and produce output like I would expect.

#include <stdio.h>

int* ar[];

int main(void) {    
    ar[0] = 97;
    ar[1] = 98;
    ar[2] = 99;

    printf("%i\n", ar[0]);
    printf("%i\n", ar[1]);
    printf("%i\n", ar[2]);
    printf("%i\n", ar[3]);

    return 0;
}

/* output
97
98
99
0
*/

我有我这样做是错误的这么多层次的感觉。是否有任何不良影响在这里,它们是什么?

I have a feeling that I'm doing this wrong on so many levels. Are there any ill effects here, what are they?

此外,为什么工作的指针作为全局变量数组,而如果我在声明它主要,GCC引发错误?

Moreover, why does the array of pointers work as global variable, while if I declare it in main, gcc raises an error?

推荐答案

至少有几个问题:

1) AR 是一个指针数组 - 你分配整数给它(和打印元素作为整数)。我得到这个警告从GCC和MSVC。

1) ar is an array of pointers - you're assigning ints to it (and printing the elements as ints). I get warnings about this from both GCC and MSVC.

2)的AR 的声明是一个不完全类型',因为它没有指定的大小。 MSVC拒绝链接说它不能解决 AR 符号,这是我的期望。 GCC做链接,提供了一个警告:

2) the declaration of ar is an 'incomplete type' since it doesn't have the size specified. MSVC refuses to link saying that it can't resolve the ar symbol, which is what I'd expect. GCC does link, providing a warning:

warning: array 'ar' assumed to have one element

我preFER在这种情况下,MSVC行为

I prefer the MSVC behavior in this case.

在GCC的情况下,你所访问的数据3或4的数组元素只有1元实际存在的,所以你访问内存不正确属于一个对象,这是不确定的行为。它会导致内存损坏,系统崩溃,或明显的工作 - 即使该程序不正确(如测试)

In GCC's case, you're accessing data for 3 or 4 array elements with only 1 element actually existing, so you're accessing memory that doesn't properly belong to an object, which is undefined behavior. It'll result in memory corruption, a crash, or apparently working - even though the program isn't correct (as in your test).

这篇关于在顶层的指针数组c没有大小声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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