【问题标题】:Segmentation fault in HackerrankHackerrank 中的分段错误
【发布时间】:2025-11-25 21:15:01
【问题描述】:

在hackerrank上练习一些问题时,我遇到了这个问题(https://www.hackerrank.com/challenges/permutations-of-strings/problem)。

代码在我的 PC 上给出了正确的输出,但在hackerrank 上出现了分段错误。请让我知道我哪里出错了??

另外,请告诉我如何纠正我的错误,以及是否有更好或有效的解决方案来解决这个问题。

上面给出了hackerrank问题的链接。

#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;
}

【问题讨论】:

  • 我没有看到任何 python 和 C++ 代码,你为什么要标记它们?
  • 您一直使用的标签不适合这个问题。请收下tour,查看what are tags and how should I use them?edit 您的帖子。请记住至少在提问时阅读您使用的标签上的鼠标悬停。
  • 抱歉使用了错误的标签。我是编程新手,这是我在 * 上的第一个问题。我认为必须使用至少 5 个有问题的标签,这就是我使用 2 个额外标签的原因。我以后不会再犯这个错误了。
  • 理解问题所需的所有信息都应包含在问题本身中。外部网站的链接可以作为补充信息,但不能替代在问题中充分说明问题。
  • @EricPostpischil 下次我会处理这件事。抱歉,问题框架不当,因为这是我在 * 上的第一个问题。

标签: c algorithm permutation


【解决方案1】:

next_permutation 中,如果字符串按降序排列,则永远不会给k 赋值。 l 也可能永远不会被赋予值。

【讨论】:

  • 但是在那个hackerrank问题中,提到输入数组总是排序的。另外,我无法弄清楚分段错误的来源。
  • @NishantBharwani:数组的初始顺序无关紧要。你的程序改变了顺序,所以最终next_permutation 以数组的降序调用。那么您的代码就有一个错误,因为它从不将值分配给kl。修复它。
  • 感谢您的帮助,让我在 * 上的第一个问题成功