gpt4 book ai didi

c - Abort 在程序中调用以打印字符串的下一个字典顺序排列

转载 作者:行者123 更新时间:2023-11-30 15:21:27 26 4
gpt4 key购买 nike

这是我的代码,它接受一个整数 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);
}
}

最佳答案

sizeof(101) 返回什么?

提示:这不是 101...

关于c - Abort 在程序中调用以打印字符串的下一个字典顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29563296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com