2016-04-25 41 views
0
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int string_cmp(const void *p, const void *q); 

int main(int argc, char **argv) 
{ 
    int i; // variable 
    char **words_array = malloc(sizeof(char*)*(argc+1)); // sets new array to hold the words 
    char *p; // another char pointer array 
    p = *words_array;  // set both equal to eachother 

    for(; *p < (argc - 1); p++) // for loop 
    { 
      p = malloc(strlen(*argv) + 1); // determines size based on user input 
      argv++; // increments 
      strcpy(p++, *argv); // copies words to the new array 

    } 
    p = NULL; // resets p 

    qsort(words_array, argc-1, sizeof(char *), string_cmp); // sorts the array 
    for(i = 0; i < argc - 1; i++){ // for loop to print properly 
      printf("%s ", words_array[i]); 
    } 
    printf("\n"); 
    return 0; 
    } 

int string_cmp (const void *p, const void *q) // compares the two different   strings and returns a value 
{ 
    const char *value = *(const char**)p; 
    const char *value_two = *(const char**)q; 

    return strcmp(value, value_two); 
} 

所以我的程序應該採用命令行參數並返回它們使用Qsort排序。例子是「./a.out你好黑暗我的老朋友應該返回黑暗的朋友你好我的老。我沒有得到任何編譯錯誤,但我得到了一個分段錯誤,我不知道如何解決這個問題。我的指針運算指針算術分割問題

+1

' p = * words_array;''words_array'的malloc在哪裏? – sjsam

+0

爲什麼你將words_array聲明爲指針的指針? – RamblinRose

+1

@sjsam malloc就在那裏,當** words_array宣佈 – EnglishStudent62

回答

-1

你遞增雙指針(的argv)即;

for(; *p < (argc - 1); p++) // for loop 
{ 
     p = malloc(strlen(*argv) + 1); // determines size based on user input 
     argv++; // increments 
     strcpy(p++, *argv); // copies words to the new array 

} 

所以將其更改爲(* argv的)++

+0

你測試過了嗎?改變後它有效嗎? – granmirupa

+0

仍然出現分段錯誤 – EnglishStudent62

-1

這些還挺建議:

變化char** argvchar* argv[]

argc返回比實際傳遞的參數數量多一個。額外的計數是針對可執行文件名稱本身的。

所以這是好做一些錯誤檢查,執行:

argc--; 
if(argc > 0) // We have some arguments 
{ 
/* Do something 
* char **words_array = malloc(sizeof(char*)*(argc+1) 
* may be changed to 
*/ 
    char **words_array; 
    words_array=malloc(argc*sizeof(char*)); 
/* Coming down 
* You could change that for-loop to something like this. 
*/ 
for(int i=0;i<argc;i++) 
    words_array[i]=argv[i]; // You have all the arguments stored in words_array 
/* Now go on sort words_array 
* and so and so forth 
*/  

} 
+0

爲什麼你在開始時遞減argc? – EnglishStudent62

+0

支持'./your_program_name Romeo Juliet',然後argc返回3.'argc'也計算'your_program_name'。所以我在開始時減少它,使其等於您傳遞的實際參數數量。 – sjsam

+0

好的一個問題是我有char ** words_array等於malloc和所有我應該不使用雙**?或者有沒有你剛使用過的原因? – EnglishStudent62

-1

的問題是在你的for循環。您比較*pargc這是沒有意義的。用標準計數器i替換環路。

for (i = 1; i < argc; i++) 

請注意,而不是argc - 1它應該被用來argc,循環應該從1開始的開始,而不是從0 此外,在循環中,您可以使用argv[i]代替*argv

+0

我需要使用指針算術,所以我不能使用這個 – EnglishStudent62