C语言中的编码挑战

时间:2018-01-12 04:52:41

标签: c

我正在尝试在C中执行以下编码挑战:

挑战: 使用C语言,使用AlphabetSoup(str)函数获取传递的str字符串参数,并按字母顺序返回字符串(即hello变为ehllo)。假设数字和标点符号不包含在字符串中。

尝试:

#include <stdio.h> 
#include <stdlib.h>

int cmpfunc(const void* val_1, const void* val_2){
    return (*(char *)val_1 - *(char *)val_2);
}

int str_size(char* str[]){
    int size = 0;
    while(str[size] != '\0')
         size++;
    return size;
}

void AlphabetSoup(char * str[]) { 
  qsort(str,str_size(str), sizeof(char), cmpfunc);
  printf("%s", str); 

}

int main(void) { 

  // disable stdout buffering
  setvbuf(stdout, NULL, _IONBF, 0);

  // keep this function call here
  AlphabetSoup(gets(stdin));
  return 0;

} 

我没有获得此代码的任何输出。我认为问题是cmpfunc函数。我没有正确实现它。我也不明白它在qsort中是如何工作的。我的理解是val_1和val_2是指向数组中两个内存块的指针,不知怎的,我必须将这些块转换为正确的类型。

我也获得了以下代码的非零状态:

void AlphabetSoup(char * str[]) {
  int str_size_ = str_size(str);
  int int_rpr[str_size_];
  int i;
  for(i = 0; i < str_size; i++){
      int_rpr[i] = (int)str[i];
  }
  printf("%i", str_size_);
    //printf("%s", str);
  //qsort(int_rpr,str_size_, sizeof(int), cmpfunc);

  //for(i = 0; i < str_size; i++){
   // printf("%c", str[i]); 
 // }

}

当我摆脱int_rpr [i] =(int)str [i];并用任何随机语句替换它,如int b; b = 0; ,它有效。

编码质询链接:Feature Request

1 个答案:

答案 0 :(得分:1)

有人要求您解析一个参数(不是来自stdin的字符串),因此您需要使用argcargv。同样sizeof(char)是C标准的1,因此是多余的。 不要复制strlen,我们有库是有原因的。

我这样做(我确认在我的系统上工作)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int char_cmp(const void *pa, const void *pb){

    char a = *((char *) pa), b= *((char *) pb);
    if (a < b){ 
        return -1;
    } else if (a > b){ 
        return 1;
    } else {
       return 0;
    }   
}

int main(int argc, char *argv[]){

char *input= NULL;
if (2 != argc){
    fprintf(stdout, "give one argument string\n");
    return 1;
} else {
    input = strdup(argv[1]);
    if (NULL == input){ 
        fprintf(stderr, "memory error\n");
        return 2;   
    }       
}   
qsort(input, strlen(input), 1, char_cmp);
fprintf(stdout, "%s\n", input);
free(input);
return 0;

}