
Donald W. answered 04/14/22
Senior Software Engineer with over 25 years of industry experience
Here's my implementation. Let me know if you have any questions about any of the code, especially around the pointer manipulation. Pointers in C can be tricky.
#include <stdio.h>
#define MAX_LENGTH 10
int *Convert(const char *str) {
int *numbers = (int *)calloc(MAX_LENGTH, sizeof(int));
for (int i=0; i<MAX_LENGTH && str[i] != 0; i++) {
numbers[i] = str[i];
}
return numbers;
}
void Print(int *numbers) {
for (int i=0; i<MAX_LENGTH && numbers[i] >= 0; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
}
int main(void) {
printf("Type something:\n");
char *buffer = malloc(MAX_LENGTH * sizeof(char));
fgets(buffer, MAX_LENGTH, stdin);
int *numbers = Convert(buffer);
Print(numbers);
free(numbers);
free(buffer);
return 0;
}
This is what the output looks like:
> ./main
Type something:
Hello
72 101 108 108 111 10 0 0 0 0
>
> ./main
Type something:
Good night to you!
71 111 111 100 32 110 105 103 104 0
>