首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

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

2013-08-13 
char (*str)[ ]和char *str[ ]作函数形参的区别下面有段代码,比较字符串大小排序。问题如下:1.用数组指针传

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

 用malloc ,和strcpy,
[解决办法]
在作为函数参数的时候
char (*p)[] =>char *p
char *str[] =>char **str
[解决办法]
我终于知道了,这个是本人调试过的。

其实,它并不是 什么溢出之类的问题。你可以跟踪一下,发现第一下就出错了。

原因是:char *s[]中的每一个变量是常量,是不可以改变的。

不信,你可以试试这个代码:
#include "stdio.h"

void main()
{
char *s = "Hello";

s[1] = 'g';
}


它是报错的。

所以,你上面的代码错误和它是一样的:strcpy(str[j],str[j+1]);,它们是不能被赋值的
[解决办法]
个人觉得,你要交换两个字符串,直接在函数里面交换char *name【】里面的值就行了。何必去写常量的地址,这样肯定会出错的,常量的地址你可以读出来,但是你不能往地址里面写东西啊,就像楼上说的一样。还有其他说的16指的是字符串长度什么的估计是乱来的,明明指的就是数组元素个数

热点排行