打印字符串时出现分段错误

Got segmentation fault on printing a String

在下面的代码中,当我尝试打印一个字符串时,错误是"segmentation fault"。 调用sort_array(str, str_tmp, N)后,strNULL.

这是为什么?

当然这就是它失败的原因:

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

void sort_array(char **str, char **str_tmp, size_t N)
{
    for (size_t i = 0; i < N; i++)
    {
        size_t j = i;

        str = realloc(str, (i+1) * sizeof(char *));

        for ( ; j != 0 && strcmp(str_tmp[i], str[j-1] ) < 0; j--)
        {
             str[j] = str[j-1];
        }

        str[j] = str_tmp[i];
    }
}

int main(void) 
{
    char *str_tmp[] = { "d", "a", "c", "b", "r", "o", "k", "f"};
    const size_t N = sizeof( str_tmp ) / sizeof( *str_tmp );
    char **str = NULL;

    sort_array(str, str_tmp, N);

    for (size_t n = 0; n < N; n++)
    {
        printf("%s ", str[n]);
    }

    putchar('\n');

    free(str);

    return 0;
}

您必须通过引用传递指针 str。否则函数处理指针的副本。即原来的指针保持不变。

给你。

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

void sort_array(char ***str, char **str_tmp, size_t n)
{
    for (size_t i = 0; i < n; i++)
    {
        size_t j = i;

        *str = realloc(*str, (i+1) * sizeof(char *));

        for ( ; j != 0 && strcmp(str_tmp[i],( *str )[j-1] ) < 0; j--)
        {
             ( *str )[j] = ( *str )[j-1];
        }

        ( *str )[j] = str_tmp[i];
    }
}

int main(void) 
{
    char *str_tmp[] = { "d", "a", "c", "b", "r", "o", "k", "f"};
    const size_t N = sizeof( str_tmp ) / sizeof( *str_tmp );
    char **str = NULL;

    sort_array(&str, str_tmp, N);

    for (size_t n = 0; n < N; n++)
    {
        printf("%s ", str[n]);
    }

    putchar('\n');

    free(str);

    return 0;
}

程序输出为

a b c d f k o r