同第一种模型实现的功能,字符串排序,但是定义的字符串方式有不同:

#include <stdio.h>
int main()
{
  int i = 0, j = 0;
  int num = 4;
  char buf[30];
  char myArray[10][30] = { "aaaaa","cccccc","bbbbb","222222" };
  
  printf("排序前:\n");
  for (i = 0; i < num; ++i)
  {
    printf("%s\n", myArray[i]);
  }
  for (i = 0; i < num; ++i)
  {
    for (j = i + 1; j < num; ++j)
    {
      if (strcmp(myArray[i], myArray[j]) > 0)
      {
        strcpy(buf, myArray[i]);               //此处交换的不是地址,而是内存
        strcpy(myArray[i], myArray[j]);
        strcpy(myArray[j], buf);
      }
    }
  }
  printf("排序后:\n");
  for (i = 0; i < num; ++i)
  {
    printf("%s\n", myArray[i]);
  }
  system("pause");
  return 0;
}

假如我们用第第一种模型封装的函数进行输出:

如图所示,直接崩溃。

为什么?

printMyArray函数:

void printMyArray1(char **buf, int num)
{
  int i;
  for (i = 0; i < num; i++)
  {
    printf("%s \n", *(buf + i));
  }
}


(buf+1)在这里代表的并不是下一个字符串首地址,因为myArray是一个二维数组,+1之后步长为300,超过了数组的长度,导致下非法的内存访问。

这样更改后即可

#include <stdio.h>
void printMyArray2(char buf[10][30], int num)
{
  int i;
  for (i = 0; i < num; i++)
  {
    printf("%s \n", *(buf + i));
  }
}
void sortMyArray2(char buf[10][30], int num)
{
  char tmpBuf[30];
  int i = 0, j = 0;
  for (i = 0; i < num; ++i)
  {
    for (j = i + 1; j < num; ++j)
    {
      if (strcmp(buf[i], buf[j]) > 0)
      {
        strcpy(tmpBuf, buf[i]);     //此处交换的不是地址,而是内存
        strcpy(buf[i], buf[j]);
        strcpy(buf[j], tmpBuf);
      }
    }
  }
}
int main()
{
  int i = 0, j = 0;
  int num = 4;
  char myArray[10][30] = { "aaaaa","cccccc","bbbbb","222222" };
  
  printf("排序前:\n");
  printMyArray2(myArray, num);
  sortMyArray2(myArray, num);
  printf("排序后:\n");
  printMyArray2(myArray, num);
  system("pause");
  return 0;
}
Last modification:February 27, 2019
If you think my article is useful to you, please feel free to appreciate