您的位置:首页 > 其它

c中的数组名的指针类型解析

2009-11-28 19:52 316 查看
下面是用来输出变量信
息的宏:

#define typeof(typevar) /
do { /
string tmp; /
cerr << "type of "#typevar" :"; /
tmp = "c++filt -t "; /
system((tmp + typeid(typevar).name()).c_str()); /
} while(0);


在这个宏定义里面,

do
{} while(0);结
构是为了让

tmp这个变量不会和别的变量产生命名冲突。用

cerr
<< “type of “#typevar”
:”而
不用

cout,是为了关闭输出缓冲,一般情况下

cout会缓冲,而

cerr是不会缓冲的。

c++filt是

binutils工具包中的一个实用程
序,用来反向解析

c++的名字修饰,它也可以用来反向解析

java中的变量名修饰。使用
这个工具的原因是

typeinfo的输出没有标准,不同的编译器输出不一样,在

g++中,比如对于

int
a[4],
输出的是

A4i,不方便阅读,如果使用的

cl编译器,就可能不需要
这个工具。

下面是测试代码:

#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;

#define typeof(typevar) / do { / string tmp; / cerr << "type of "#typevar" :"; / tmp = "c++filt -t "; / system((tmp + typeid(typevar).name()).c_str()); / } while(0);
int main() {
int a[3][4];

cout << "prototype of a: int a[3][4]:/n";
typeof(a);
typeof(*a);
typeof(&a);
typeof(a+1);
typeof(*(a+1));
typeof(*(a+1)+1);
typeof(a[1]);
typeof(1[a]);
typeof(a[1] + 1);

int b[4];
cout << "/n/n";
typeof(b);
typeof(&b);
//typeof(&(&b)); // error, &b is lvalue
typeof(*(&b));
typeof(b+1);
typeof(*(b+1));
typeof(&b + 1);
//typeof(&(b+1)); // error, invalid lvalue
typeof(*b);

int c[3][4][5];
cout << "/n/n";
typeof(c);
typeof(*c);
typeof(&c);
typeof(c+1);
typeof(*(c+1));
//typeof(&(c+1)); // error, invalid lvalue

int d[1][4];
cout << "/n/n";
typeof(d);
typeof(*d);
typeof(&d);
typeof(d+1);
typeof(*(d+1));
return 0;
}


[/code]
输出结果:

prototype
of a:
int a[3][4]:

type
of a :int
[3][4]

type
of *a :int
[4]

type
of &a
:int (*) [3][4]

type
of a+1 :int
(*) [4]

type
of *(a+1)
:int [4]

type
of *(a+1)+1
:int*

type
of a[1] :int
[4]

type
of 1[a] :int
[4]

type
of a[1] + 1
:int*

type
of b :int
[4]

type
of &b
:int (*) [4]

type
of *(&b)
:int [4]

type
of b+1 :int*

type
of *(b+1)
:int

type
of &b + 1
:int (*) [4]

type
of *b :int

type
of c :int
[3][4][5]

type
of *c :int
[4][5]

type
of &c
:int (*) [3][4][5]

type
of c+1 :int
(*) [4][5]

type
of *(c+1)
:int [4][5]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: