下列程序输出结果为多少?
#include <stdio.h>
#include <string.h>
#define TRACE(S)(printf("%s\n",#S),S)
int main(){
int a=5;
int b=TRACE(a);
const char *str="hello";
char des[50];
strcpy(des,TRACE(str));
printf("%s\n",des);
return 0;
}
结果:
a
str
hello
分析:
printf("%s\n",#S)
#进行宏字符串连接,会被解析为
printf("%s\n","S")
所以做TRACE(a)、TRACE(str)的时候输出的并非是5和hello,而是它们本身,a和str
再者,宏定义是一个逗号运算符,由printf和S两项组成,所以TRACE(str)的值为后面的值,即str
2、使用宏定义求结构体的内存偏移地址
#include <stdio.h>
#include <string.h>
#define OffSet(type,field)((size_t)&(((type*)0)->field))
struct str{
char a;
int b;
float c;
double d;
char e;
};
int main(){
printf("%d\n",OffSet(str,a));
printf("%d\n",OffSet(str,b));
printf("%d\n",OffSet(str,c));
printf("%d\n",OffSet(str,d));
printf("%d\n",OffSet(str,e));
return 0;
}
3、#define和typedef 的区别
#include <stdio.h>
#include <string.h>
#define INTPTR1 int*
typedef int * INTPTR2;
int a=1;
int b=2;
int c=3;
const INTPTR1 p1=&a;
const INTPTR2 p2=&b;
INTPTR2 const p3=&c;
int main(){
p1=&c;
printf("%d\n",*p1);
*p2=20;
printf("%d\n",*p2);
*p3=30;
printf("%d\n",*p3);
return 0;
}
以上写法是正确的,但是
*p1=10;
p2=&a;
p3=&a;
都是错误的
即:
const INTPTR1 p1表示p1是一个常量指针,不可以通过p1去修改p1指向的内容,但是p1可指向其他内容
const INTPTR2 p2表示p2是一个指针常量,不可使p2再指向其他内容,但可以通过p2修改其指向内容
p3与p2同