1. 指针数组:
int *a[5];
char *str[5];
指针数组主要用来操作字符串数组,通常将指针数组的每个元素存放字符串的首地址实现对多个字符串的操作。
二维数组主要用来存储字符串数组,通过每行存储一个字符串,多行存储多个字符串所组成的数组
2. 指针和二维数组的关系:
int a[2][3] = {0};
int *p = NULL;
int (*q)[3] = NULL;p = &a[0][0];
p = a[0];
p = *a;
q = a;
二维数组的数组名是指向数组第一行元素的数组指针
访问二维数组第m行第n列的方式:
a[m][n]*(a[m]+n)*(*(a+m)+n)*(p+m*n+n)*(*(q+m)+n)*(q[m]+n)q[m][n]
二维数组传参:
int a[2][3] = {0};
int Fun(int (*parray)[3], int len);char str[5][32] = {0};
int Fun(char (*pstr)[32], int len);
3. 二级指针:
1. 指针数组传参时:
int *a[5] = {NULL}; //a是int **型
char *pstr[5] = {"hello", "world", "how", "are", "you"}; //str是char **型int Fun(char **ppstr, int len);
作业:
1. 现有二维数组 char str[5][32] = {"hello", "world", "how", "are", "you"};
封装函数实现对所有字符串的排序
封装函数实现对所有字符串的打印
#include <stdio.h>
#include <string.h>int InputStr(char (*pstr)[32], int len)
{int i = 0;for(i = 0; i < len; i++){gets(pstr[i]);}return 0;
}int SortStr(char (*pstr)[32], int len)
{int i = 0;int j = 0;char tmp[32] = {0};for(j = 0; j < len-1; j++){for(i = 0; i < len-1-j; i++){if(strcmp(pstr[i], pstr[i+1]) > 0){strcpy(tmp, pstr[i]);strcpy(pstr[i], pstr[i+1]);strcpy(pstr[i+1], tmp);}}}return 0;
}int OutputStr(char (*pstr)[32], int len)
{int i = 0;for(i = 0; i < len; i++){printf("%s\n",pstr[i]);}return 0;
}int main(void)
{char str[5][32] = {0};InputStr(str,5);SortStr(str,5);printf("==================\n");OutputStr(str,5);return 0;
}
2. 现有指针数组 char *pstr[5] = {"hello", "world", "how", "are", "you"};
封装函数实现对所有字符串的排序
封装函数实现对所有字符串的打印
#include <stdio.h>
#include <string.h>int SortStr(char **pstr, int len)
{int i = 0;int j = 0;char *tmp = NULL;for(j = 0; j < len-1; j++){for(i = 0; i < len-1-j; i++){if(strcmp(pstr[i], pstr[i+1]) > 0){tmp = pstr[i];pstr[i] = pstr[i+1];pstr[i+1] = tmp;}}}return 0;
}int OutputStr(char **pstr, int len)
{int i = 0;for(i = 0; i < len; i++){printf("%s\n",pstr[i]);}return 0;
}int main(void)
{char *str[5] = {"Hello", "World", "How", "Are", "You"};SortStr(str,5);OutputStr(str,5);return 0;
}