I get a "undefined reference to log10"
You need to link your program with the math library using -lm
.
But this is just a start. Fix the following issues:
a) allocate extra character for null string terminator if you want your string to be properly terminated.
b) scanf("%d",x);
requires pointer to x
c) int
variable cannot store 17
numbers, use long int
d) you cannot store int
into char array
, your digit has to be converted to ASCII
char.
f) your algorithm stores characters in a reverse order, you need to reverse your string
e) allocated memory has to be freed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void reverse_in_place(char * str, size_t len) {
size_t i, j;
for (i = 0, j = len - 1; i < j ; i++, j--) {
char a = str[i];
char z = str[j];
str[i] = z;
str[j] = a;
}
}
int main(void){
long int x;
int i;
printf("enter x:\n");
scanf("%ld",&x);
int numOfDigits = (int) (log10(x) + 1);
printf("numOfDigits = %d\n", numOfDigits);
char* arr = calloc(numOfDigits + 1, 1);
for(i=0; i < numOfDigits; i++){
arr[i] = (char) ((x % 10) + '0');
printf(" %c", arr[i]);
x /= 10;
}
reverse_in_place(arr,strlen(arr));
printf("\nFirst num is: %c in string %s",arr[0], arr);
free(arr);
return 0;
}
Output:
enter x:
451236789012345678
numOfDigits = 18
8 7 6 5 4 3 2 1 0 9 8 7 6 3 2 1 5 4
First num is: 4 in string 451236789012345678