大学阶段不常见的C语言表达
这些用法容易忘记,因为我不常用啊,每次都要翻书,今天写出来以后就不要查书了。
重定向
输入重定向例子: F:\C_Study\temp1\temp1.exe < F:\C_Study\temp1\myword.txt 把这个文档中的数据输入到程序。
输出重定向例子: F:\C_Study\temp1\temp1.exe > F:\C_Study\temp1\myword.txt 输出到这个文本文档。
输出重定向追加: F:\C_Study\temp1\temp1.exe << F:\C_Study\temp1\myword.txt
函数指针
char (*f)()=getfirst;
int (*f2)(int a,double b)=max;
返回类型 (*指针名)(函数参数);
const 修饰指针
const int *p=a; //p指向的数据不可改变;
int * const p=a;//p不可指向别的内存;
const int * const p=a;//指向的数据不可改变,p不可指向别处内存。
命令行参数
#include"stdio.h"
int main(int argc,int *argv[])
{
printf("%d ",argc);
for(int i=1;i<argc;i++)
{
printf("%s\n",argv[i]);
}
return 0;
}
volatile
用于硬件地址和其他并行程序共享的数据。
防止编译器对代码优化。直接读取原内存中数据。
const volatile 不能被程序改变,可以被程序以外的代理改变。
restrict
修饰指针。表示该指针是访问的唯一方式。//这样就可以让编译器优化代码。
memcpy() 和 memmove()
memcpy(void * restrict s1,const void *restrict s2,size_t n);//从 s2 把 n 个字节复制到 s1。s1 和 s2 不可重复。
memmove(void * restrict s1,const void *restrict s2,size_t n);//从 s2 把 n 个字节复制到 s1;
文件操控函数
fseek(文件指针,long类型偏移字节,起始位置)//SEEK_SET,SEEK_CUR,SEEK_END,成功返回0,否则返回1.
ftell(文件指针),返回当前偏移的字节数
fread(),fwrite(),feof()等等等等。本阶段用不到,这里不详举例了。
伸缩数据
struct a
{
int a1;
char a2[];
};
struct a *p=(struct a *)malloc(sizeof(struct a)+10*sizeof(char));
free(p);
指针
int *a[3][4] //12个指针。指向 int *类型。
int (*a)[3][4] //一个指针,指向 int[3][4]。
int (*a[3])[4] //三个指针,只想 int[4].
char (*f)() //函数指针。指向char。
char (*f[3])() //3个指向 char的函数指针。
位字段
#include"stdio.h"
#include"stdlib.h"
typedef struct colour
{
int a1:1;//一位
int a2:2;//两位
int :1;//无名的一位。可用于对齐。
int :0;//强制对其到下一个字节。
int a3:10;//10位。
}colour;
int main(int argc,int *argv[])
{
colour a;
a.a1=1;
a.a2=3;
return 0;
}
编译预处理
##粘合。#粘合字符串。如 #define xname(n) x##n
__VA_ARGS__ 可变参数。如 #define PR(...) printf(__VA_ARGS__) 。 如#define PR(x,...) printf("mess"#x":"__VA_ARGS__)
#define limit 20
const int lim=50;
const int data[limit];//不能用 lim
static int data2[limit];//不能用 lim
#ifdef xxx //和 #if define(xxx) 等价。判断是否被定义。
# .....
#else
# .....
#endif
#ifnde xxx
# .....
#endif
#if SYS == 1
# ...
#endif
#if SYS == 1
# ...
#elif SYS == 2
# ....
#elif SYS == 3
# ...
#else
# ...
#endif
#if EOF == 1
#error not c99
#endif
#line 1000 "abc.c" //把当前行号重置为 1000 文件名置为 abc.c
可变参数函数
#include"stdio.h"
#include"stdarg.h"//可变函数头文件
int sum(int geshu,...)
{
va_list ap;//存放参数的变量。
int total=0;
va_start(ap,geshu);//把 ap 初始化为 参数列表。
for(int i=0;i<geshu;i++)
{
total+=va_arg(ap,int);
}
va_end(ap);
return total;
}
int main(int argc,int *argv[])
{
int a=sum(5,1,2,3,4,5);
printf("%d",a);
return 0;
}