-
Cannot find my error
Hi there, I am trying to create a function that takes in any integer and convert it into a string. For example 1000 ---> "1000".
I have gone through an hour trying to figure out my error, but I just can't find it, so I've decided to seek help...here's my code:
Code:
#include <stdio.h>#include <stdlib.h>
#include <math.h>
#include <string.h>
char intToCh(int i) {
char char_result;
char character_array[36] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char_result = character_array[i];
return char_result;
}
char* string_of_int;
char* intToString(int integer) {
int len_of_int = log10(integer) + 1;
int expon = log10(integer);
int divider;
int i = 0;
for(i = 0; i < len_of_int; i++) {
int temp;
if (integer == 0) {
break;
} else {
divider = pow(10, expon);
temp = integer / divider;
string_of_int[i] = intToCh(temp);
}
integer = integer - (temp * divider);
expon--;
}
return string_of_int;
}
int main(void) {
intToString(1000);
printf("%s\n", string_of_int);
return 0;
}
The compile errors:
Code:
/tmp/cctRlDcq.o: In function `intToString':IntToString.c:(.text+0xe3): undefined reference to `log10'
IntToString.c:(.text+0x100): undefined reference to `log10'
IntToString.c:(.text+0x137): undefined reference to `pow'
collect2: ld returned 1 exit status
I am really confused by the undefined reference because I have already included the math.h library, but it seems like it's not recognized.
Thank you,
-Genxi
-
"undefined reference to" normally means a linking error; try linking to the needed library.
I would guess the math library; this library is often called just by the letter m.
Edit: You say you already linked to math.
You might try casting the types to double; IIRC some old compilers required that the signature match.
Edit2: Nearly all linkers require the library/object files to be in the correct order; the order changes for compiler brands.
Tim S.
-
Hey Tim,
I've tried compiling with the following:
Code:
gcc -Wall -o IntToString IntToString.c -lm
but, after I ran the code, it gave me the segmentation fault.
Any more ideas?
-Genxi
-
Allocate space for what string_of_int points to.
Tim S.
-
Thank you for your advices, Tim! I got my code to work after allocating some space and linking by -lm. -high five-!!!
-
Hmmm ... just use snprintf() if you have a C99 compiler, sprintf() otherwise.
Code:
snprintf(string_of_int, <WHATEVER_SIZE_YOU_ALLOCATED>, "%d", 1000);