尝试定义用户类型时,我偶然发现了一个我不太明白的错误:以下代码工作正常
const int a[5] = { 1, 2, 3, 4, 5 };
typedef const int costant;
costant b = 5;
costant *c = a;
void func( const int item )
{
printf("Item: %i\n", item );
}
int main( void )
{
func( a[0] );
func( b );
func( *c );
}
尽管如此,初始化指针
costant *c = a[0];
未能说明Initializer element is not costant
。尝试访问位置a[0]
更改其内容被拒绝,并出现错误 assignment of read-only location
.
为什么被认为是数组地址a
作为 const 但不是其元素 a[0]
,即使它是“只读”?
替换 typedef
与 #define costant const int
不会改变行为。
最佳答案
与 #define
的语法为 #define NEW_SYMBOL [old_symbol]
不同,typedef
的语法为:
typedef existing_type new_type;
所以:
typedef const int constant;
C 有效,而
typedef constant const int;
不是。
关于c - 指针初始化无法识别定义的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41467792/