Linux 内核C语言深度解析 复习笔记

编程入门 行业动态 更新时间:2024-10-27 19:28:46

Linux <a href=https://www.elefans.com/category/jswz/34/1769575.html style=内核C语言深度解析 复习笔记"/>

Linux 内核C语言深度解析 复习笔记

一.
在 GNU C 中,通过数组元素索引,我们就可以给某个指定的元素直接赋值

#include <stdio.h>int main(){int a[100] = {[10]=1, [20]=2, [30]=3};for(int i = 1;i <= 3;i++){printf("%d\n", a[i*10]);}return 0;
}
/*output:
1
2
3
*/
~         

二.
GNU C 支持使用 … 表示范围扩展,这个特性不仅可以使用在数组初始化中,也可以使用在switch-case 语句中。

实验代码:

#include <stdio.h>
#include <string.h>void print(int count, ...){int *p = &count - 1;printf("count_addr: %p\n", &count);for(int i = 0;i < count;i++){printf("%d\n", *p);p -= 1;}
}int main(int argc, char *argv[]){int a[100] = { [0 ... 9]=7, [10 ... 19]=7 };print(4, 1, 2, 3, 4);for(int i = 0;i < 21;i++){if(a[i]){printf("%d",a[i]);}if((i+1) % 10 == 0)putchar('\n');}return 0;
}
/*output:
count_addr: 0x7ffd34346a2c
1152
32696
-68417024
21873
7777777777
7777777777
*/

看到这输出 有点莫名奇妙,然后用gdb 调试跟进print函数去看参数在栈上的分配情况,然后我傻了


count参数跟其他传进print的参数的地址不连续…, 靠count的指针无法输出其他参数,64位是这个结果,不清楚32位可不可以正确输出,如果把 void print(int count, …), 改成void print(int count, int a, int b, int c, int d) 就可以正确输出…

三——语句表达式
语句表达式的定义:
GNU C 是对 C标准作了扩展,允许在一个表达式里内嵌语句, 允许在表达式内部使用局部变量,for循环和goto跳转语句。这样的表达式,我们称之为语句表达式。

语句表达式的值总等于最后一个表达式的值。

( { 表达式1;表达式2;表达式3;} )

实验程序

#include <stdio.h>int main(int argc, char *argv[]){char *s = "This is a test", *s2 = NULL;s2 = ({1;2;3;s;});if(s2)puts(s2);return 0;
}
/*output:
This is a test
*/

其他C语言的巧妙用法还是看 体验课复习吧,内容太多了

更多推荐

Linux 内核C语言深度解析 复习笔记

本文发布于:2023-07-28 17:50:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267567.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内核   深度   语言   笔记   Linux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!