strcpy给出分段错误

时间:2019-09-20 22:28:18

标签: 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)并没有帮助。

1 个答案:

答案 0 :(得分:0)

可以使用

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