嵌入式第十二天!(指针数组、指针和二维数组的关系、二级指针)

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;
}

最近更新

  1. TCP协议是安全的吗?

    2024-01-29 09:10:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-29 09:10:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-29 09:10:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-29 09:10:03       18 阅读

热门阅读

  1. Android Okhttp断点续传

    2024-01-29 09:10:03       32 阅读
  2. 贪吃蛇游戏设计文档(基于C语言)

    2024-01-29 09:10:03       36 阅读
  3. 网路服务器——线程池技术

    2024-01-29 09:10:03       31 阅读
  4. 小世界网络 | 小世界网络(Python)

    2024-01-29 09:10:03       36 阅读
  5. myql入门

    2024-01-29 09:10:03       31 阅读
  6. Redis面试题35

    2024-01-29 09:10:03       31 阅读