1. typedef 和struct 用法
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Node{
int a;
struct Node *next;
}Node,*Node_p;
typedef struct Node Nod;
void main (){
struct Node *list =(struct Node *)malloc(sizeof(struct Node)); //不加typedef时,可这样用struct 定义
Node *tmp= NULL; //typedef 定义 strcut Node为Node 类型
struct Node *list2 =NULL; //不用typedef, 直接用struct Node也行
Node_p list3 = NULL; //typedef 定义 strcut Node *为Node_p 类型
list->a = 1;
list->next = NULL;
list2 = (struct Node *)malloc(sizeof(struct Node));
list->next = list2;
list2->a = 2;
list3 = (Nod *)malloc(sizeof(Nod)); //typedef定义struct Node为Nod 类型
list3->a = 3;
list3->next = NULL;
list2->next = list3;
tmp = list;
while (tmp) {
printf("node->a=%d\n",tmp->a);
tmp = tmp->next;
}
free(list2);
free(list);
free(list3);
}
2. c语言中typeof关键字
typeof(int *) a,b;
等价于:
int *a,*b;
//内核工作队列的用法,内核上实际是 定义了cpu_worker_pools这个全局变量,每个cpu 都是NR_STD_WORKER_POOLS维worker_pool数组。
typeof (struct worker_pool[NR_STD_WORKER_POOLS]) cpu_worker_pools
如果将typeof用于表达式,则该表达式不会执行,只会得到表达式的类型,以下示例声明了int类型的var变量,因为表达式foo()是int类型的,由于表达式不会被执行,所以不用调用foo()函数
extern int foo();
typeof(foo()) var; //相当于等同去int var;
使用typeof的声明限制
typeof构造中的类型名不能包含存储类说明符,如
extern或static.不过允许包含类型限定符,
如const或volatile.例如,下列代码是无效的.因为它在typeof构造中声明了extern;
typeof(extern int) a;
下列代码使用外部链接来声明标识符b是有效的,表示一个int类型的对象.下一个声明也是有效的,它声明了一个使用const限定符的char类型指针,表示指针p不能被修改.
extern typeof(int) b;
typeof(char*const) p;//常指针,不能修改指针指向;
在宏声明中使用typeof
typeof构造的主要应用是用在宏定义中。可以使用typeof关键字来引用宏参数的类型
3. container_of & offset_of
下面typeof就是获取type成员member的类型,还是奇怪为什么这里要周转一次,案例直接将ptr强转也没问题吧?
#define container_of(ptr,type,member) ({\
const typeof(((type *)0)->member) *_mptr = ptr; \
(type *)((char*)(_mptr) - offset_of(type,member));})
#define offset_of(TYPE,MEMBER) ((size_t)&((TYPE*)NULL)->MEMBER)
4. C++/C 宏定义(define)中# ## 的含义
define 中的# ## 一般是用来拼接字符串的,但是实际使用过程中,有哪些细微的差别呢,我们通过几个例子来看看。
#是字符串化的意思,出现在宏定义中的#是把跟在后面的参数转成一个字符串;
eg:
|
1
2
3
|
#define strcpy__(dst, src) strcpy(dst, #src)
strcpy__(buff,abc) 相当于 strcpy__(buff,“abc”)
|
##是连接符号,把参数连接在一起
|
1
2
3
|
#define FUN(arg) my##arg
则 FUN(ABC)
等价于 myABC
|
转自:C语言中如何使用宏连接多个字符串(#和##的用法)_不积跬步,无以至千里!-程序员资料_宏连接字符串 - 程序员资料
#define SOFTWARE_VERSION "Software:V1.00"
#define HARDWARE_VERSION "Hardware:V1.00"
#define SYSTEM_VERSION SOFTWARE_VERSION##" "##HARDWARE_VERSION
但是,经过实际测试,以上的代码,只能用于KEIL/ADS/IAR等集成编译环境中。如果是在linux下,使用gcc编译器的话,上述代码就会出错,目前尚未查出具体原因。经过一番折腾后,发现gcc环境下,如果要连接多个字符串,直接使用空格连接就行了。所以将其改为如下语句就可以了:
#define SOFTWARE_VERSION "Software:V1.00"
#define HARDWARE_VERSION "Hardware:V1.00"
#define SYSTEM_VERSION SOFTWARE_VERSION HARDWARE_VERSION
5.sizeof
typedef struct Node{
int num;
struct Node *next;
}Node;
Node **a= {0};
printf(" is %d size=%d Node=%d\n",sizeof(a[0]),sizeof(**a),sizeof(Node));
is 4 size=8 Node=8
6. const char*const* argv
**argv = x; // not allowed because of the first const
*argv = y; // not allowed because of the second const
argv = z; // allowed because no const appears right next to the argv identifier
9万+

被折叠的 条评论
为什么被折叠?



