I'm a beginner in c and I'm trying to writing a program that gets two strings, those strings are numbers.
- I need to sum those string without converting it to int type.
- I can assume that the string will not start with zero (char type of course).
- I need to use dynamic allocation memory, in order to return the exact size of the sum string, and the string cannot start with zeros (again char) at the beginning of the string (from left side).
this function is returning a pointer to the start address if the sum string number. and no require to free the allocated memory.
For example:
"104104" + "203203" = "307307"
"8875643" + "8756875876533987" = "8756875885409630".
"0" + "765" = "765"
etc..
Thanks for the helpers!
EDIT: Im adding the code I wrote, this is before we get new instructions to use only string manipulation. my implement for that exercise was to convert the string to int.
#define _CRT_SECURE_NO_WARNINGS
#include "Utils.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
long long int ReturnAsInt(char* arr) {
double str_to_int, sum_of_arr = 0;
int arr_len;
// convert string a to int.
arr_len = strlen(arr);
for (int i = 0; i < strlen(arr); i++) {
// multipy the char with 10 pow i (in order to sum each char and create long int of the number).
str_to_int = (arr[i] - '0') * pow(10, arr_len);
sum_of_arr += str_to_int;
arr_len--;
}
// removing unnessacry 0 at the end of the number.
sum_of_arr = sum_of_arr / 10;
return sum_of_arr;
}
char* AddNumbers(char* num1, char* num2)
{
char char_in_sum;
char *allocate_mem, *save_addr_mem;
long long int num1_in_int, num2_in_int, sum_of_arrys, copy_sum_of_arrys;
int counter = 0, num_in_sum;
num1_in_int = ReturnAsInt(num1);
num2_in_int = ReturnAsInt(num2);
sum_of_arrys = num1_in_int + num2_in_int;
// allocate 1 btye from the heap memory, this memory will be reallocate.
allocate_mem = (char*) calloc(1, sizeof(char));
if (allocate_mem == NULL) {
exit(1);
}
// save the start address of the heap memory.
save_addr_mem = allocate_mem;
copy_sum_of_arrys = sum_of_arrys;
while (copy_sum_of_arrys) {
num_in_sum = copy_sum_of_arrys % 10;
copy_sum_of_arrys = copy_sum_of_arrys / 10;
// convert the number to char. '0' value is 48 in int.
char_in_sum = '0' + num_in_sum;
// char_in_sum = 48 + num_in_sum;
allocate_mem[counter] = char_in_sum;
counter++;
// reallocate memory.
allocate_mem = (char*) realloc(allocate_mem, sizeof(char) + counter);
if (allocate_mem == NULL) {
exit(1);
}
}
allocate_mem = (char*)realloc(allocate_mem, sizeof(char) + counter);
allocate_mem[counter] = '\0';
// do reverse to the araray.
char temp;
for (int i = 0; i < strlen(allocate_mem); i++) {
if (i < counter) {
counter--;
temp = allocate_mem[i];
allocate_mem[i] = allocate_mem[counter];
allocate_mem[counter] = temp;
}
}
return allocate_mem;
}