-2

Am trying to convert user's input of at least 17 characters into an array. Say for example the user's input is 25281582252, by using x = arr[1] , 5 is assigned to variable x. I've not had success yet. I get a "undefined reference to log10" with gcc on linux. Here is my code

#include <stdio.h>
#include <math.h>

int main(){
    int x;

    printf("enter x");
    scanf("%d",x);
    int numOfDigits = log10(x) + 1;
    char* arr = calloc(numOfDigits, sizeof(char));
    for(int i=0;i<numOfDigits;i++,x/=10){
        arr[i] = x % 10;
    }

    printf("first num: %d",arr[0]);
    return 0;
}

Thanks in advance

sg7
  • 6,108
  • 2
  • 32
  • 40
alvo
  • 27
  • 2
  • 6

1 Answers1

1

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
sg7
  • 6,108
  • 2
  • 32
  • 40