下面是一个递归函数,应该将整数转换为字符串
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)
并没有帮助。
答案 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;
}