大學階段不常見的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;
}