c - strcpy给出段错误

标签 c recursion strcpy

以下是应该将整数转换为字符串的递归函数

char* int_to_word(int word_int){
    static char new[2];
    char alphabet[26]={"abcdefghijklmnopqrstuvwxyz"};
    new[0]=alphabet[word_int%27-1];
    //new[1]='\0';
    if(word_int/27==0){
        return new;
    }
    static char *word;
    strcpy(word,strcat(int_to_word(word_int/27),new));
    return word;
}


strcpy(word,strcat(int_to_word(word_int/27),new));> 26时,我在行word_int上遇到了分段错误。据我所知,没有理由它不起作用。我最好的猜测是,我在复制到word之前需要以某种方式分配它,但是将初始化程序更改为static char *word=(*char)malloc(100)并没有帮助。

最佳答案

可以使用static变量。 span计算转换后的值所需的字符数。 index用于使用span - index从零开始迭代分配的内存。
由于letters具有26个字符,因此请使用% 26获取一个字符的值,并使用/ 26减小原始值以计算下一个字符。
12345将转换为sgv

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

char *number_str ( int x);

int main ( void) {
    char *value = NULL;
    if ( ( value = number_str ( 0))) {
        printf ( "%s\n", value);
        free ( value);
    }
    if ( ( value = number_str ( -12345))) {
        printf ( "%s\n", value);
        free ( value);
    }
    if ( ( value = number_str ( 26))) {
        printf ( "%s\n", value);
        free ( value);
    }
    return 0;
}

char *number_str ( int x) {
    char *out = NULL;
    static char const *letters = "abcdefghijklmnopqrstuvwxyz";
    static size_t index = 0;
    static size_t span = 0;
    if ( x == 0) {
        if ( NULL == ( out = malloc ( span + 1 + ( 0 == span)))) {
            fprintf ( stderr, "malloc problem\n");
            return NULL;
        }
        out[span + ( 0 == span)] = 0;//zero terminate
        if ( 0 == span) {
            out[0] = 'a';//when the original value of x is zero
        }
        index = span;
        return out;
    }
    else {
        if ( 0 == span) {
            index = 0;
            if ( x != abs ( x)) {
                span++;//add one for leading '-'
            }
        }
        span++;
        out = number_str ( x / 26);//recursive call
    }
    if ( out) {
        int sign = 0;
        if ( x != abs ( x)) {
            out[0] = '-';//set leading '-'
            sign = 1;
        }

        int digit = x % 26;
        out[span - index + sign] = letters[abs ( digit)];
        index--;//span - index to iterate from 0 to span
        if ( ! span || ( out[0] == '-' && 1 == span)) {
            //the last iteration. reset to zero
            index = 0;
            span = 0;
        }
    }
    return out;
}

关于c - strcpy给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58035780/

相关文章:

c++ - 使用 Eclipse 编译 xerces-c++ 程序

c - atoi 的 Valgrind 错误

c++ - strcpy_s 不适用于 gcc

c - 在 C 中使用 strcpy() 和复制 char* 的地址之间的区别

C字符串函数错误

c - 在 C 中,对指针使用 typedef 是一种好形式吗?

c++ - extern "C"extern 变量在 C++ 程序中作为类变量寻求..如何声明它?

recursion - F#:互递归数据结构的变态

r - 在 R 中建立家庭嵌套树父/子关系

recursion - 递归地将每隔一个元素移动到列表的末尾