char (*str)[ ]跟char *str[ ]作函数形参的区别


char (*str)[ ]和char *str[ ]作函数形参的区别
下面有段代码,比较字符串大小排序。问题如下:

1.用数组指针传参时,交换字符串排序ok;

2.在用指针数组传参时,要通过交换字符串来排序出错。求大神解答?

  //数组指针
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    void sort(char(p)[20], int n);
    int i;
    char str[4][20];
    
    cout << "enter 4 strings:";
    for(i = 0; i < 4; i++)
        cin >> str[i];
    sort(str, 4);
    
    cout << "Now,the 4 strings:" << endl;
    for(i = 0; i < 4; i++)
        cout << str[i] << " ";
    cout << endl;
    return 0;
}
void sort(char(
p)[20], int n)
{
    int i, j;
    char str1[20];//注意定义,str1则会出错
    for(i = n - 1; i > 0; i--)
    {
        for(j = 0; j < i; j++)
        {
            if(strcmp(
(p + j), (p + j + 1)) > 0)
            {
                strcpy(str1, 
(p + j));
                strcpy((p + j), (p + j + 1));
                strcpy((p + j + 1), str1);
            }
        }
    }
}
//指针数组
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    void sort(char 
 str[], int n);
    int i;
    char *name[] = {"wo", "ai", "zhong", "guo", "xin"};
    int n = 5;
    sort(name, n);



相关链接

c语言 函数 程序开发

在下不在的说 10 years, 7 months ago

Your Answer