Abort在程序中调用,用于打印字符串的下一个字典排列

时间:2015-04-10 13:54:16

标签: c string

这是我的代码,它将整数s作为输入,这是我希望它处理的字符串数,然后它将s字符串作为输入。对于它们中的每一个,它应该输出字母的最大字​​典排列,最小的字母。问题是它编译得很好,但在运行时崩溃了,我真的不知道为什么。有什么建议吗?

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

 int compare(const void *a, const void * b);
 void swap(char* a, char* b);
 int findCeil (char* str, char first, int l, int h);
 void nextPermutation(char* w);


int main(void){
    int s;
    char* w;
    scanf("%d", &s);
    while(s--){
        w = (char*)malloc(sizeof(101));
        if(w == NULL){ printf("Malloc failed.\n"); return 1;}
        scanf("%s", w);
        nextPermutation(w);
        free(w);
    }
    return 0;
}


//function for qsort()
int compare(const void *a, const void * b){
  return ( *(char *)a - *(char *)b );
}

//utility function 
void swap(char* a, char* b){
    char t = *a;
    *a = *b;
    *b = t;
}

/* This function finds the index of the smallest character
    which is greater than 'first' and is present in str[l..h]*/
int findCeil (char str[], char first, int l, int h){
    int ceilIndex = l;
    int i;
    // find the smallest character greater than first
    for (i = l+1; i <= h; ++i)
      if (str[i] > first && str[i] < str[ceilIndex])
            ceilIndex = i;
    return ceilIndex;
}

void nextPermutation(char* w){
    int size = strlen(w);
    int i;    
    // Find the rightmost character which is smaller than its next
    // character. Let us call it 'first char'        
    for(i = size - 2; i >= 0; --i){
        if(w[i] < w[i+1])
            break; 
    }
    // If there is no such chracter, all are sorted in decreasing order, 
    //it means we are done.
    if(i == -1)
        printf("no answer\n");
    else{
        int ceilIndex = findCeil(w, w[i], i + 1, size - 1 );     
        // Swap first and second characters
        swap( &w[i], &w[ceilIndex] );
        // Sort the string on right of 'first char'
        qsort( w + i + 1, size - i - 1, sizeof(w[0]), compare );
        printf("%s\n", w);
    }
}

2 个答案:

答案 0 :(得分:1)

sizeof(101)返回什么?

提示:它不是101 ......

答案 1 :(得分:0)

问题是您尝试使用malloc(sizeof(101))。使用它时,它实际上为您分配了int大小的内存,这可能不是您的意思。 我猜您的意思是malloc(sizeof("101")),因为您稍后将其转换为char*。或者您可能希望使用malloc(101)来获取确切的内存大小。