![](/img/trans.png)
[英]Not allocating memory for pointers, is this causing my segmentation fault (core dumped) in C?
[英]Segmentation fault (core dumped) allocating memory?
我在運行此程序時收到錯誤“Segmentation fault(core dumped)”。 我是c編程的新手,所以它可能是愚蠢的東西,但我無法弄明白。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void swap(char *x, char *y){
char temp = *x;
*x=*y;
*y=temp;
}
char** getPermutations(char *string){
int length = strlen(string);
int startIndex = 0;
int endIndex = length - 1;
if(startIndex == endIndex){
printf("%s\n", string);
}else{
for(int j = startIndex; j<=endIndex; j++){
swap((string + startIndex),(string + j));
getPermutations(string);
swap((string+startIndex),(string+j));
}
}
}
int main(int argc, char *argv[]){
if(argc>2){
printf("\nToo Many arguments\n");
exit(0);
}else{
printf("%s",argv[1]);
char * str = malloc(strlen(argv[1]) + 1);
strcpy(str,argv[1]);
getPermutations(str);
}
}
您的問題是getPermutations
無休止地調用自己。 你需要傳遞額外的東西才能知道何時停止。 就像它一樣,它只是一遍又一遍地調用自己,直到你有一個堆棧溢出。
此外,您已設置getPermutations
以返回char**
,但之后您永遠不會返回任何內容。 所以這也很奇怪。
我的建議:
將函數的返回類型更改為void
因為它不返回任何內容。
將函數的名稱更改為printPermutations
因為它只打印排列。
提供一種結束遞歸的方法。 將startIndex
作為參數傳遞。
傳遞字符串的長度,這樣每次遞歸調用函數時都不會計算它。
將比較運算符更改為>=
以考慮零長度字符串。
void printPermutations(char *string, int startIndex, int length){
int endIndex = length - 1;
if(startIndex >= endIndex){
printf("%s\n", string);
}else{
for(int j = startIndex; j<=endIndex; j++){
swap((string + startIndex),(string + j));
printPermutations(string, startIndex+1, length);
swap((string+startIndex),(string+j));
}
}
}
並稱之為:
printPermutations(str, 0, strlen(str));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.