The following is a recursive function that is supposed to turn an integer into a string
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;
}
I'm getting a segmentation fault with the line strcpy(word,strcat(int_to_word(word_int/27),new));
when word_int
> 26. To my knowledge, there's no reason it shouldn't work. My best guess is that I somehow neeed to allocate word
before copying into it, but changing the initializer to static char *word=(*char)malloc(100)
did not help.
static
variables can be used. span
counts the number of characters needed for the converted value. index
is used to iterate through the allocated memory starting from zero using span - index
.
Since letters
has 26 characters, use % 26
to get the value of one character and / 26
to reduce the original value for calculation of the next character.
12345
will be converted to 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.