//指针数组
char *p1[]={"123","456","789"}
//二位数组
char p2[3][4]={"123","456","789"}
//手动分配二维内存
//char *array[3]
char **p3 = (char **)malloc(3 * sizeof(char *))
for (i = 0; i < 3; i++)
{
p3[i] = (char *), alloc(10 * sizeof(char));
sprintf(p3[i], "%d %d", i, i);
}
一:指针数组:创建,做形参,排序
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
void print_array(char **p, int n)
//void print_array(char *p[],int n)//指针数组作为形参的俩种方式。
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("%s, ", p[i]);
}
printf("\n");
}
void sort_array(char **p, int n)
{
int i, j;
char *tmp;
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(p[i], p[j])>0)
{
tmp = p[i];
p[i] = p[j];
p[j] = tmp;
}
}
}
}
int main(void)
{
char *p[] = { "000000000", "5555555555", "aaaaaaaaa", "333333333" };
//p[0] = "000000000";
int n = sizeof(p) / sizeof(p[0]);
printf("排序前:\n");
print_array(p, n);
sort_array(p, n);
printf("\n排序后:\n");
print_array(p, n);
printf("\n");
system("pause");
return 0;
}
二:二维数组:创建,做形参,排序
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
//void print_array_err(char **a, int n)//这是错误的,退化为指针后的步长为4,而二维数组步长为30
//void print_array(char (*a)[30], int n)//这个也是对的
void print_array(char a[][30], int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
//printf("%s\n", a[i]);
printf("%s\n", *(a + i));//首行地址 和首行首元素地址一样
}
printf("\n");
return 0;
}
void sort_array(char a[][30], int n)
{
int i = 0;
int j = 0;
char tmp[30];
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(a[i], a[j])>0)
{
//交换的内存块
strcpy(tmp, a[i]);
strcpy(a[i], a[j]);
strcpy(a[j], tmp);
}
}
}
return 0;
}
int main(void)
{
char a[][30] = { "000000000", "5555555555", "aaaaaaaaa", "333333333" };
int n = sizeof(a) / sizeof(a[0]);
char b[] = "aaaaaa";
printf("%d\n", sizeof(b));//结果是7 计算的是内存的大小
printf("%d\n", strlen(b));//结果是6 计算的是字符的数量
printf("排序前\n");
print_array(a, n);
sort_array(a, n);
printf("\n排序后\n");
print_array(a, n);
printf("\n");
system("pause");
return 0;
}
三:手动分配二维内存:创建
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
char **getMem(int n)//分配内存空间
{
int i = 0;
char **buf = (char **)malloc(n*sizeof(char *));//char *buf[3]
if (buf == NULL)
{
return NULL;
}
for (i = 0; i < n; i++)
{
buf[i] = (char *)malloc(30 * sizeof(char));
char str[30];
sprintf(str, "text%d%d", i, i);
strcpy(buf[i], str);
}
return buf;
}
void print_buf(char **buf, int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("%s, ", buf[i]);
}
printf("\n");
}
void free_buf(char **buf, int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
free(buf[i]);
buf[i] = NULL;
}
if (buf != NULL)
{
free(buf);
buf = NULL;
}
}
int main(void)
{
int n = 3;
char **buf = NULL;
buf = getMem(n);//创建
print_buf(buf, n);//打印
free_buf(buf, n);//释放
buf = NULL;
printf("\n");
system("pause");
return 0;
}