1. qsort() 快速排序函数调用
#include<stdlib.h>
void qsort(void *base, size_t n_elements, size_t el_size, int (*compare)(const void *, const void *));
其中第一个参数为数组首地址,第二个参数为数组长度,第三个参数为每个元素的类型长度,第四个参数为需要实现的比较函数地址。
#include<stdio.h>
#include<stdlib.h>
int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
int main()
{
int a[] = {2, 3, 1, 5, 4};
int i;
qsort(a, 5, sizeof(int), cmp);
for(i=0; i<5; i++)
{
putchar(a[i]+'0');
putchar('\n');
}
return 0;
}
2. 指针数组与数组指针
#include <stdio.h>
int main()
{
int a[2][2] = {{1,2},{3,4}};
int (*p)[2]; // 数组指针,可以这样赋值p=a,不能是p=a[]
char *s[2] = {"hello", "world"}; // 指针数组,是一维数组
p = a;
printf("%d, %d, %d, %d\n", (*p)[0], (*p)[1], (*(p+1))[0], (*(p+1))[1]);
printf("%s %s\n", s[0], s[1]);
return 0;
}
3. 若干误解纠正
http://blog.youkuaiyun.com/rjzou2006/archive/2008/04/15/2292698.aspx
数组名不完全等于指针。虽然数组名可以转换为指向其指代实体的指针,但是它只能被看作一个指针常量,不能被修改。
数组名作为函数形参时,在函数体内,其失去了本身的内涵,仅仅只是一个指针。
在WIN32平台下,指针长度为4,无论指针类型为何。
sizeof不是一个函数,是一个操作符。语句sizeof(int)就可以说明sizeof的确不是一个函数。
二维数组实际是一维数组。
4. 文件读写操作
putc / getc 字符读写函数
#include<stdio.h>
#include<stdlib.h>
#define TEST puts("test");
int main()
{
FILE *fp;
char ch, filename[10];
scanf("%s", filename);
fp = fopen(filename, "w");
ch = getchar(); // 吸纳回车
ch = getchar();
while(ch != '#')
{
putc(ch, fp); // 同fputc
putchar(ch);
ch = getchar();
}
fclose(fp);
fp = fopen(filename, "r");
puts("++++++++");
while(!feof(fp))
{
ch = getc(fp);
if(ch == EOF) // EOF为文件结束标志
continue;
printf("%c", ch);
}
fclose(fp);
exit(0);
}
fprintf / fscanf 格式化读写函数
#include<stdio.h>
int main()
{
FILE *r, *w;
char str1[20];
char str2[20];
r = fopen("hello.txt", "r");
w = fopen("hello.txt", "w");
fprintf(w, "hello\nworld");
fflush(w);
fscanf(r, "%s %s", str1, str2);
puts(str1);
puts(str2);
fclose(r);
fclose(w);
return 0;
}
rewind() 使位置指针重新返回文件的开头
5. 函数指针
#include<stdio.h>
int max(int x, int y)
{
return (x>y) ? x : y;
}
int min(int x, int y)
{
return (x<y) ? x : y;
}
int sum(int x, int y)
{
return x+y;
}
void process(int x, int y, int (*func)(int, int))
{
int result;
result = (*func)(x, y);
printf("%d\n", result);
}
int main()
{
process(1, 2, max);
process(1, 2, min);
process(1, 2, sum);
return 0;
}
6. 存储单元动态分配
#include<stdio.h>
#include<malloc.h>
int main()
{
int size = 20;
char *a = (char*)malloc(size);
a[0] = 'h';
a[1] = 'i';
a[2] = '\0';
puts(a);
free(a);
return 0;
}
7. 随机数
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int x;
srand(time(0));
x = rand();
printf("%d\n", x);
return 0;
}