Hackerrank 中的分段错误
Segmentation fault in Hackerrank
我在 hackerrank 上练习一些问题时遇到了这个问题 (https://www.hackerrank.com/challenges/permutations-of-strings/problem)。
该代码在我的 PC 上给出了正确的输出,但在 hackerrank 上出现了分段错误。请让我知道哪里出错了??
此外,请告诉我如何纠正我的错误,以及是否有更好或有效的解决方案来解决这个问题。
上面给出了 hackerrank 问题的 link。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char **str1_ptr, char **str2_ptr)
{
char *temp = *str1_ptr;
*str1_ptr = *str2_ptr;
*str2_ptr = temp;
}
void reverse(int index, char **s, int n)
{
int x = n - 1;
for (int i = index; i < n; i+=2)
{
swap(&s[i], &s[x]);
x--;
}
}
int next_permutation(int n, char **s)
{
/**
* Complete this method
* Return 0 when there is no next permutation and 1 otherwise
* Modify array s to its next permutation
*/
int k, l, flag = 0;
char *temp;
for (int i = 0; i <= n - 2; i++)
{
if (strcmp(s[i], s[i + 1]) < 0)
{
k = i;
flag = 1;
}
}
for (int i = k + 1; i < n; i++)
{
if (strcmp(s[k], s[i]) < 0)
{
l = i;
}
}
swap(&s[k], &s[l]);
// temp = s[k];
// s[k] = s[l];
// s[l] = temp;
reverse(k + 1, s, n);
if (flag)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
char **s;
int n;
scanf("%d", &n);
s = calloc(n, sizeof(char *));
for (int i = 0; i < n; i++)
{
s[i] = calloc(11, sizeof(char));
scanf("%s", s[i]);
}
do
{
for (int i = 0; i < n; i++)
printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
} while (next_permutation(n, s));
for (int i = 0; i < n; i++)
free(s[i]);
free(s);
return 0;
}
在 next_permutation
中,如果字符串按降序排列,k
永远不会被赋值。 l
也可能永远不会被赋值。
我在 hackerrank 上练习一些问题时遇到了这个问题 (https://www.hackerrank.com/challenges/permutations-of-strings/problem)。
该代码在我的 PC 上给出了正确的输出,但在 hackerrank 上出现了分段错误。请让我知道哪里出错了??
此外,请告诉我如何纠正我的错误,以及是否有更好或有效的解决方案来解决这个问题。
上面给出了 hackerrank 问题的 link。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char **str1_ptr, char **str2_ptr)
{
char *temp = *str1_ptr;
*str1_ptr = *str2_ptr;
*str2_ptr = temp;
}
void reverse(int index, char **s, int n)
{
int x = n - 1;
for (int i = index; i < n; i+=2)
{
swap(&s[i], &s[x]);
x--;
}
}
int next_permutation(int n, char **s)
{
/**
* Complete this method
* Return 0 when there is no next permutation and 1 otherwise
* Modify array s to its next permutation
*/
int k, l, flag = 0;
char *temp;
for (int i = 0; i <= n - 2; i++)
{
if (strcmp(s[i], s[i + 1]) < 0)
{
k = i;
flag = 1;
}
}
for (int i = k + 1; i < n; i++)
{
if (strcmp(s[k], s[i]) < 0)
{
l = i;
}
}
swap(&s[k], &s[l]);
// temp = s[k];
// s[k] = s[l];
// s[l] = temp;
reverse(k + 1, s, n);
if (flag)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
char **s;
int n;
scanf("%d", &n);
s = calloc(n, sizeof(char *));
for (int i = 0; i < n; i++)
{
s[i] = calloc(11, sizeof(char));
scanf("%s", s[i]);
}
do
{
for (int i = 0; i < n; i++)
printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
} while (next_permutation(n, s));
for (int i = 0; i < n; i++)
free(s[i]);
free(s);
return 0;
}
在 next_permutation
中,如果字符串按降序排列,k
永远不会被赋值。 l
也可能永远不会被赋值。