Could you fix my code please? (i get no output after inputing the number)

Joined
Oct 16, 2023
Messages
1
Reaction score
0
#include <stdio.h>
int get_number_of_digits(int x){
int j = 1, c = 1;
while (x / j >= 10) {
j *= 10;
c += 1;
}
return c;
}
void get_digits(int x, int T[], int size) {

int j = 1, v = x;
int i;
for (i = 0; i < size - 1; i++) {
T = v / j;
v = v % j;
j /= 10;
}
T[size - 1] = v;
}

int main() {
int x;
printf("Enter a number : ");
scanf("%d",&x);

const int n = get_number_of_digits(x);

int *digits_stocker = (int *)malloc(n * sizeof(int));

get_digits(x, digits_stocker, n);

int k;

for (k = 0; k < n; k++) {
printf("T = %d\t", digits_stocker[k]);
}

free(digits_stocker);

return 0;
}
 
Joined
Oct 17, 2023
Messages
2
Reaction score
0
One of the mistakes that you do is in the line: T[I] = v / j;[/I]

Here, you are trying to set the value of the actual pointer and not the value it points to. You need to dereference it instead to modify the actual value. However, you do another mistake. You convert the number to a series of another number that will contain each digit. That doesn't make any sense... You should instead convert it to a string and print it at once! In that case, we will start from the end of the buffer.

Here is a modified code (with comments) that works as you expect it to works:

C:
#include <stdio.h>
#include <stdlib.h>

int get_number_of_digits(int x){
  int j = 1, c = 1;

  while (x / j >= 10) {
    j *= 10;
    c += 1;
  }

  return c;
}

void get_digits(int num, char* buffer, int digit_count) {
  buffer += digit_count - 1; // We start from the end

  /* Starting from the last digit to the first */
  do {
    *buffer = num % 10; // Get the number of the digit
    buffer -= 1;        // Go to the previous location in the pointer
    num /= 10;       // "Trim" the last digit of the number
  } while(num > 0);  // While the number gets "0"
}

int main() {
  int num;
  printf("Enter a number : ");
  scanf("%d", &num);

  const int digit_count = get_number_of_digits(num);

  // Allocate one extra byte for the null terminator
  char* buffer = (char*)malloc(digit_count * sizeof(char) + 1);
  buffer[digit_count] = '\0'; // Add the null terminator

  get_digits(num, buffer, digit_count);

  for (int k = 0; k < digit_count; k++) {
    printf("Character #%d = %d\n", k + 1, buffer[k]);
  }

  free(buffer);

  return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,795
Messages
2,569,644
Members
45,358
Latest member
TreyTritt8

Latest Threads

Top