指针是C语言中比较重要的一章。其实书中是这么写的,说是指针很重要,但是在基础的C语言中感觉看不到它重要在哪里了,知道后来学了数据结构,增、删、改、查都要用到指针的时候才知道了它的重要性。
这里写一点简单的指针使用:
目录
// 冒泡排序==快速排序
void test3(int a[], int n) {
int i, j, temp, *p;
printf("原数组排序:");
for(p=a; p<a+n; p++) printf("%2d", *p);
printf("\n选择法由大到小排序:");
for(i=0; i<n; i++) {
p = a + i;
for(j=1; j<n-i; j++) {
if(*p < *(p+j)) temp = *p, *p = *(p+j), *(p+j) = temp, printf("%d<-->%d\n", *p, *(p+j));
}
}
for(p=a; p<a+n; p++) printf("%2d", *p);
printf("\n冒泡法由小到大排序:");
for(i=0, p=a; i<n; i++) {
for(j=0; j<n-i-1; j++) {
if(*(p+j) > *(p+j+1)) temp = *(p+j), *(p+j) = *(p+j+1), *(p+j+1) = temp, printf("%d<-->%d\n", *(p+j), *(p+j+1));
}
}
for(p=a; p<a+n; p++) printf("%2d", *p);
}
// 快排
void test02_while(char *arr, int left, int right) {
char *i, *j, *k;
char temp;
if(left < right) {
i = j = k = arr + left;
temp = *(arr + left);
//printf("%c,%c,%d,%d\n",*i, temp, left, right);
while( i < arr + right) {
if( *i < temp ) {
//printf("%c,%c,%s\n", temp, *i, arr);
*j = *i;
j++;
k = i;
while( k > j) {
*k = *(k-1);
k--;
}
*k = temp;
}
i++;
}
test02_while(arr, left, j - arr);
test02_while(arr, j - arr + 1, right);
}
}
+函数--作用在函数名
// 指针函数:类型名 *函数名(参数列表) (输出而为数组中的第i行的全部数值)
void test5() {
int* testSearch_test5(int (*p)[3], int row);
int arr[3][3] = {1, 2, 3, 4, 5, 60, 7, 8, 9};
int row, col;
int * value;
for(row = 0; row < 3; row++) {
value = testSearch_test5( arr, row);
for(col = 0; col < 3; col++) {
if(*(value + col) < 60) printf("第%d行中小于60的数值有第%d个数值: %d\n", row, col, *(value + col));
}
}
}
+指针--作用在形参
// 指针数组:类型名 *数组名[数组长度] (将字二维符串数组排序)
void test6() {
void sort_test6(char* str[], int n);
char* str[6] = {"what of it !", "I'd never seen in my life !", "What's the hell on !"};
sort_test6(str, 3);
}
void sort_test6(char* str[], int n) {
int row1, row2;
char* value;
for(row1 = 0; row1 < n; row1++) {
for(row2 = row1 + 1; row2 < n; row2++) {
if(strcmp(str[row1], str[row2])) value = str[row1], str[row1] = str[row2], str[row1] = value;
}
}
for(row1 = 0; row1 < n; row1++) printf("%s\n", str[row1]);
}
+指针(变量)
// 指针指针: 数据类型 *(*指针变量)
void test7() {
char* str[6] = {"what of it !", "I'd never seen in my life !", "What's the hell on !"};
char **p;
int row, col;
p = str;
for(row = 0; row < 3; row++) {
printf("%s, %s, %s\n", *(p + row), *(str+row), str[row]);
printf("%d, %d, %d\n", p + row, str + row, str + row);
}
}