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);
for(i = 0; i < n; i++)
cout << name[i] << " ";
cout << endl;
return 0;
}
void sort(char *str[], int n)
{
int i, j;
char *temp;
//char temp[10];//改成temp[10]为何不行?
for(i = n - 1; i > 0; i--)
{
for(j = 0; j < i; j++)
{
//交换字符串地址
if(strcmp(str[j], str[j+1]) > 0)
{
temp = str[j];
str[j] = str[j+1];
str[j+1] = temp;
}
//交换字符串,出错?
// if(strcmp(str[j], str[j+1]) > 0)
// {
// strcpy(temp,str[j]);
//strcpy(str[j],str[j+1]);
// strcpy(str[j+1],temp);
//}
}
}
}
if(strcmp(str[j], str[j+1]) > 0)
{
temp = str[j];
str[j] = str[j+1];
str[j+1] = temp;
}
#include "stdio.h"
void main()
{
char *s = "Hello";
s[1] = 'g';
}