2012-11-22 61 views
0

我想通过交换指针来对一个char指针(char * _string)数组进行排序。通过交换指针,C++对char数组排序char

我有这个方法,我想要做的就是使用我从_string得到的值,并且不通过操作_string,而是对我将该方法交给的空帮助程序数组(char * _output)进行排序。

任何人都可以帮助我,告诉我我做错了什么吗?

void sortAsc(char* _string, char* _output) 
{ 

    int length = strlen(_string); 

     // output and string now point to the same area in the memory 
    _output = _string; 

    for(int i = 0; i < length; i++) { 
      for(int j = 0; j < length; j++) { 
       if(*(_output) > (_output[j])) { 

        // save the pointer 
        char* tmp = _output; 

        // now output points to the smaller value 
        _output = _output+j; 

        // move up the pointer to the smaller value 
        _output + j; 

        // now the pointer of the smaller value points to the higher value 
        _output = tmp; 

        // move down to where we were + 1 
        _output - j + 1; 

      } 
     } 
    } 

    //_output[length]='\0'; 

    //delete chars; 
} 

在我的主法,我做这样的事情:

char * string = {"bcdae"}; 
char * output = new char[5]; 
sortAsc(string, output); 

代码后,我想输出数组包含排序值。

+0

这是什么问题呢?为我们提供一些示例输入和输出或您遇到的错误。 –

+4

'_output = _string'之后,您将失去对传递给函数的帮助程序数组的引用,当然这没有帮助。 – Jack

+0

编译后输出变量应该是“abcde”。 此时,程序不会抛出任何错误,但调用该方法后输出变量仍为空。 –

回答

0

让我们使用指针表示法对10个大小的int数组进行选择排序,您可以简单地将其更改为数组列表。

 *---*---*---*---*---* ........ 
a[] = | 1 | 2 | 4 | 0 | 3 | ........ 
     *---*---*---*---*---* ........ 
     ^--------We start here looking for the smaller numbers and sort the array. 


for(i = 0; i < 10; i++){ 
    k = i; 
    bypass = *(a + i); 
    for(j = i + 1; j < 10; j++){ 

     /* To get Increasing order. */ 
     if(bypass > *(a + j)){ 
      bypass = *(a + j); 
      k = j; 
     } 
    } 
    if (k != i){ 
     *(a + k) = *(a + i); 
     *(a + i) = bypass; 
    } 
} 
0

这个排序字符串转换为已分配的缓冲区,如果缓冲区不够大,无法告诉你它有多么大的是:

std::size_t sortAsc(char const* string, char* dest, std::size_t dest_length) { 
    std::size_t str_length = strlen(string); 
    char const* str_end = string + str_length; 
    if (dest_length < str_length+1) 
    return str_length+1; 
    std::copy(string, str_end, output); 
    output[str_length] = '\0'; 
    std::sort(output, output+strlen(output)); 
    return str_length+1; 
} 

这确实可怜“分配一个新的字符串”格局使用上面的实现:

char* allocate_and_sortAsc(char const* string) { 
    std::size_t str_length = strlen(string); 
    char* retval = new char[str_length+1]; 
    std::size_t count = sortAsc(string, retval, str_length+1); 
    ASSERT(count <= str_length); 
    return retval; 
} 

,不使用的变量名与_开始,这是一个不好的做法,因为它真的徘徊近编译器保留的名称。全球范围内保留_Capital,全球保留_lower,到处保留foo__bar

+0

@Abhishek不,我不会删除“将缓冲区的最后一个字符设置为”\ 0''“,缓冲区溢出/失败以正确终止是C代码中最常见的严重安全错误之一。 – Yakk

+0

@oluies你为什么要批准C++代码中的编辑?您的个人资料至少不会显示C++专业知识。 – Yakk