2012-11-22 41 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