C program not running properly on raspberry pi - c

I'm currently designing a hemming code. This code works perfectly on my computer but when I port it over to my pi, it just does not work properly. I have no idea why and I am pretty new at C and the raspberry pi. Any help would be greatly appreciated.
Below is my full code:
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int main(void){
int bitLen, errorLoc;
printf("\nLength of the data bits: ");
scanf("%d", &bitLen);
char binStr[ bitLen ], binStrErr[ bitLen ];
printf("Data stream without error: ");
scanf("%s", &binStr);
if(strlen(binStr) > bitLen || strlen(binStr) < bitLen)
{
printf("\nLength of data stream given does not match stated input length!");
return 0;
}
printf("Location of data bit that has error: ");
scanf("%d", &errorLoc);
if(errorLoc > bitLen)
{
printf("\nValue given is bigger than the input length!");
return 0;
}
//Number Of Check Bits Needed
int rBit = 1;
while (pow(2, rBit) < (bitLen + rBit + 1))
{
rBit = rBit + 1;
}
int checkBitsArr[rBit];
int checkBitsErrArr[rBit];
//Actual size of array
bitLen = bitLen + rBit;
int binNum[bitLen];
int binNumErr[bitLen];
int size = sizeof(binNum) / sizeof(binNum[0]);
int binNumPos = size;
printf("\nData stream: ");
//Flipping the error bit and storing into another string
printf("\nOriginal data stream: ");
for (int i = 0; i < strlen(binStr); i++){
printf("%c", binStr[i]);
if(i == (strlen(binStr)) - errorLoc){
int temp = ((binStr[i] - '0') == 0) ? 1 : 0;
binStrErr[i] = temp + '0';
}
else{
binStrErr[i] = binStr[i];
}
}
printf("\nData stream with error: ");
for (int i = 0; i < strlen(binStr); i++){
printf("%c", binStrErr[i]);
}
//Filling in the bits into two arrays: One is the correct data stream and one with error
for (int i = strlen(binStr); i >= 0; i--)
{
binNum[binNumPos] = binStr[i] - '0';
binNumErr[binNumPos] = binStrErr[i] - '0';
binNumPos--;
}
printf("\n\n");
//Moving bits to left to make space
int position = 1;
for (int i = size - 1; i >= 0; i--)
{
if ((position & (position - 1)) == 0)
{
for (int c = 0; c <= i; c++)
{
binNum[c - 1] = binNum[c];
binNumErr[c - 1] = binNumErr[c];
}
binNum[i] = 33;
binNumErr[i] = 33;
}
position++;
}
//Settings check bits into place
position = 1;
int checkBitIndex = 0;
for (int i = size - 1; i >= 0; i--)
{
//Get check bit position
if ((position & (position - 1)) == 0)
{
int temp = 0;//number of 1s in relation to the check bit
int tempErr = 0;
int maxNum = (i - position) + 1;
if (maxNum < 0)
maxNum = maxNum + (-1 * maxNum);
//first part of check
while (maxNum < i)
{
if (binNum[maxNum] == 1)
{
temp++;
}
if (binNumErr[maxNum] == 1)
{
tempErr++;
}
maxNum++;
}
int startNum = (i - position) + 1;
//If the start number is less than zero, make it zero
if (startNum < 0)
startNum = startNum + (-1 * startNum);
//Skip check method. Get the next set of check values in relation to the current check bit
for (int x = startNum - (position * 2); x >= 0; x = x - (position * 2))
{
int k = 0;
while (k < position)
{
if (binNum[x + k] == 1)
{
temp++;
}
if (binNumErr[x + k] == 1)
{
tempErr++;
}
k++;
}
}
//Set the value of check bit
binNum[i] = (temp % 2 == 0) ? 0 : 1;
binNumErr[i] = (tempErr % 2 == 0) ? 0 : 1;
//Replace the current value with the correct checkbit
checkBitsArr[checkBitIndex] = binNum[i];
checkBitsErrArr[checkBitIndex] = binNumErr[i];
temp = 0;
tempErr = 0;
checkBitIndex++;
}
position++;
}
printf("\nSEC code: ");
printf("\nOriginal data stream: ");
for (int i = 0; i < size; i++)
{
printf("%d", binNum[i]);
}
printf("\nData stream with error: ");
for (int i = 0; i < size; i++)
{
printf("%d", binNumErr[i]);
}
printf("\n\n");
int checkIndex = (int)pow(2, rBit - 1);
printf("\n\nCheckbits of data bits without error: \n");
for (int i = checkBitIndex - 1; i >= 0; i--)
{
printf("C%d: %d ", checkIndex, checkBitsArr[i]);
checkIndex = checkIndex/2;
}
checkIndex = (int)pow(2, rBit - 1);
printf("\n\nCheckbits of data bits with error: \n");
for (int i = checkBitIndex - 1; i >= 0; i--)
{
printf("C%d: %d ", checkIndex, checkBitsErrArr[i]);
checkIndex = checkIndex/2;
}
checkIndex = (int)pow(2, rBit - 1);
int posError = 0;
printf("\n\nSyndrome code: \n");
for (int i = checkBitIndex - 1; i >= 0; i--)
{
int x = checkBitsErrArr[i] ^ checkBitsArr[i];
if(x == 1){
posError += checkIndex;
}
printf("C%d: %d ", checkIndex, x);
checkIndex = checkIndex/2;
}
printf("\n\n");
printf("\nPosition of error: %d\n\n", posError);
// printf("\n\n");
return 0;
}
These are the inputs for the scanf:
Length of the data bits: 16
Data stream without error: 0011001100110011
Location of data bit that has error: 8
Below are my results on both computer and pi:
Computer result (correct):
Pi result (wrong):

Looks like you have far more than just one problem, but let's just start with the first one:
char binStr[ bitLen ], binStrErr[ bitLen ];
The string you are requesting next contains not just the 16 bytes you get as input, but also an additional sentinel character as the 17th character.
So at this point you already had 2 buffer overflows, which you can already see nicely in the output from the Pi. The same buffer overflow also occurs in the first example, except the memory layout is different enough so that it doesn't yield visible artifacts.
for (int c = 0; c <= i; c++)
{
binNum[c - 1] = binNum[c];
binNumErr[c - 1] = binNumErr[c];
}
Here comes the next buffer overflow, respectively actually an underflow this time. You are writing to binNum[-1] which is a memory location outside of the memory binNum is pointing to.
Anyway, a buffer overflow means the behavior of your program is undefined.
Get used to valgrind or similar tools for checking your code for undefined with regard to such errors.

Related

A variable in a for loop is changing without being supposed to change in c

Here is the code:
#include <stdio.h> // printf
#include <cs50.h> // get_long
#include <string.h> // strlen
#include <stdlib.h> // stdlib
int credit_test(string input);
int main(void)
{
string userInput;
// Gets user input, and tests if input is valid
bool isInvalid = false;
do
{
userInput = get_string("Number: "); // Prompts user for input
for(int i = 0, evenIndex = strlen(userInput); evenIndex > i; i++)
{
if(userInput[i] - 48 >= 0 && userInput[i] - 48 <= 9 && (strlen(userInput) == 15 || strlen(userInput) == 16)) // Tests if input is valod
{
isInvalid = false;
}
else
{
isInvalid = true;
break;
}
}
}
while(isInvalid);
int keyValidity = credit_test(userInput);
}
int credit_test(string input)
{
int inputLen;
inputLen = strlen(input);
// Even number calculation
int evenArr[16];
int evenSum = 0;
int evenIndex = 0;
printf("Length: %i\n", inputLen);
for(int i = 0; inputLen > i; i++)
{
int n = i * 2;
evenArr[evenIndex] = input[n] * 2;
if(evenArr[evenIndex] > 0)
{
evenArr[evenIndex] -= 96;
}
if(evenArr[evenIndex] > 9) // Code to split doubles
{
int doubleNum = evenArr[evenIndex];
evenArr[evenIndex] = 1;
evenIndex++;
evenArr[evenIndex] = doubleNum % 10;
}
evenIndex++;
evenSum += evenArr[i];
printf("%i\n", evenArr[i]);
printf("Length: %i\n", inputLen);
}
printf("Length: %i\n", inputLen);
printf("Even Sum: %i\n", evenSum);
// Odd number calculation
int oddArr[16];
int oddSum = 0;
int oddIndex = 1;
for(int i = 0; 16 > i; i++)
{
oddArr[i] = input[oddIndex];
if(oddArr[i] > 0)
{
oddArr[i] -= 48;
}
oddSum += oddArr[i];
oddIndex += 2;
printf("%i\n", oddArr[i]);
}
printf("Odd Sum: %i\n", oddSum);
// Validity test
int finalSum = evenSum + oddSum;
int cardType = finalSum % 10;
printf("Final Sum: %i\n", finalSum);
if(cardType == 0 && (input[0] - 48) == 5)
{
printf("MasterCard \n");
}else if (cardType == 0 && (input[0] - 48) == 4)
{
printf("Visa \n");
}else if(cardType == 0 && (input[0] - 48) == 3)
{
printf("Amex \n");
}else
{
printf("Invalid \n");
}
return 0;
}
I just cannot wrap my head around why, but if you run the code, and keep an eye on the "inputLen" variable it stays what it should be, but in the first for loop which gets the even number in the input, the inputLen stays the same, which is correct, but when the loop finishes, for some reason, the variable changes to 0? So would anyone mind to explain as to why its happening? And sorry if the code is all wonky and bad :)
Thanks so much.
This part of the loop
for(int i = 0; inputLen > i; i++)
{
int n = i * 2;
evenArr[evenIndex] = input[n] * 2;
//...
invokes undefined behavior because the expression input[n] can access memory beyond the used array due to using the expression i * 2 as an index. For example then i is equal to inputLen - 1 then n will bi initialized by the expression 2 * ( inputLen - 1 ) and the value of the expression you are using as an index to access elements of the array input but the array does not have so many elements.
Also in this code snippet
if(evenArr[evenIndex] > 9) // Code to split doubles
{
int doubleNum = evenArr[evenIndex];
evenArr[evenIndex] = 1;
evenIndex++;
evenArr[evenIndex] = doubleNum % 10;
}
evenIndex++;
the variable evenIndex can be incremented twice that again can be a reason of undefined behavior when this variable is used as an index to access elements of the array evenArr.

Is there a way to include more than one 'if' conditional for output?

I have this code below (whole code after this section). I am wanting to include more than one casse for this section of the code:
for(i = 0; i < length; i++)
{
if(numberArray[i] == 1)
{
casse = 2;
}
if(numberArray[i] == 2)
{
casse = 3;
}
if(numberArray[i] == 1 || numberArray[i] == 2)
{
casse = 4;
}
}
So far, the above prints '4' when the value '8213' is entered. This is expected since for each round of for loop the 'casse' variable gets updated, by the time it runs the last integer in the array, the value for 'casse' has undergone many replacements and the end result is the last replacement of '4'.
The objective of the code is to determine which cases (casse) have
been met. There can be more than one case (casse) being met, but as it
stands now, it only has room for one case.
#include <stdio.h>
#include <math.h>
int main(void) {
int odo, value, casse;
int i;
printf("please enter a value for the odometer:\n");
scanf("%d", &odo);
value = odo;
casse = 0;
int length = floor(log10(abs(odo))) + 1;
/* count number of digits */
int c = 0; /* digit position */
int n = value;
while (n != 0)
{
n /= 10;
c++;
}
int numberArray[c];
c = 0;
n = value;
/* extract each digit */
while (n != 0)
{
numberArray[c] = n % 10;
n /= 10;
c++;
}
for(i = 0; i < length; i++)
{
printf("%d, ", numberArray[i]);
}
for(i = 0; i < length; i++)
{
if(numberArray[i] == 1)
{
casse = 2;
}
if(numberArray[i] == 2)
{
casse = 3;
}
if(numberArray[i] == 1 || numberArray[i] == 2)
{
casse = 4;
}
}
printf("\n%d\n", casse);
return 0;
}
Output:
please enter a value for the odometer:
8213
3, 1, 2, 8,
4
Expected output:
please enter a value for the odometer:
8213
3, 1, 2, 8,
Not only '4', but also '3', '2'.
Rather than a single variable that keeps track of the last case, you want an array which keeps track of all cases. For a small number of cases, the array can be a fixed size, with the index as case number and the value in the array as the number of times that case was triggered:
int cases[5] = {0};
for(i = 0; i < length; i++)
{
if(numberArray[i] == 1)
{
cases[2]++;
}
if(numberArray[i] == 2)
{
cases[3]++;
}
if(numberArray[i] == 1 || numberArray[i] == 2)
{
cases[4]++;
}
}

Two-Way Insertion Sort not sorting

This is supposed to be a Two-Way insertion sort, but it's not sorting. I'm also supposed to print out the number of assignments for sorting, but right now I just want it to sort.
A separate output array of size 2n+1 is set aside. Initially x[0] is placed into the middle element of the array n.
Continue inserting elements until you need to insert between a pair of elements in the array.
As before you need to make room for the new element by shifting elements. Unlike before,
you can choose to shift all smaller elements one step to the left or all larger elements one step
to the right since there is additional room on both sides of the array. The choice of which
shift to perform depends on which would require shifting the smallest amount of elements.
I can't find much on the internet about this sort except that no one uses it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printArray(int arr[], int len) {
for (int j = 0; j < len; j++)
printf("%d ", arr[j]);
printf("\n");
}
int main() {
FILE *in;
int size_arr = 0;
char ch;
if ((in = fopen("data_a5.txt", "r")) == NULL) {
printf("Error!");
exit(1);
}
do {
ch = fgetc(in);
if (ch == '\n')
size_arr++;
} while (ch != EOF);
rewind(in);
int arr[size_arr];
int sort_arr[2 * size_arr + 1];
int n = 0;
while (!feof(in)) {
fscanf(in, "%d", &arr[n]);
n++;
}
fclose(in);
for (n = 0; n < 2 * size_arr; n++) {
sort_arr[n] = 0;
}
sort_arr[size_arr] = arr[0];
for (n = 1; n < size_arr; n++) {
int index = size_arr;
if (arr[n] <= sort_arr[size_arr]) {
while (!(arr[n] <= sort_arr[index]) && sort_arr[index] != 0 && index >= 0) {
index--;
}
}
if (arr[n] > sort_arr[size_arr]) {
while (!(arr[n] <= sort_arr[index]) && sort_arr[index] != 0 && index < 2 * size_arr) {
index++;
}
}
if (sort_arr[index] == 0) {
sort_arr[index] = arr[n];
} else {
int next_R, next_L = index;
while (sort_arr[next_R] != 0 && next_R <= 2 * size_arr) {
next_R++;
}
while (sort_arr[next_L] != 0 && next_L >= 0) {
next_L--;
}
int R_move = next_R - index;
int L_move = index - next_L;
if (R_move > L_move) {
while (L_move <= index) {
sort_arr[L_move] = sort_arr[L_move + 1];
L_move++;
}
sort_arr[index] = arr[n];
} else {
while (R_move >= index) {
sort_arr[R_move] = sort_arr[R_move - 1];
R_move--;
}
sort_arr[index] = arr[n];
}
}
}
printArray(arr, size_arr);
return 0;
}
I'm not sure this solves all problems but it is a problem you must fix.
This code
int next_R, next_L = index;
while(sort_arr[next_R] != 0 && next_R <= 2*size_arr)
has undefined behavior as next_R is uninitialized.
Maybe you want:
int next_R = index, next_L = index;
^^^^^
while(sort_arr[next_R] != 0 && next_R <= 2*size_arr)
In any case you have to initialize next_R before using it.
I also find this line strange:
printArray(arr, size_arr);
^^^
Seems you are printing the original array instead of the sorted array.
May be you want:
printArray(sort_arr, size_arr);
^^^^^
There are some problems in your code:
when you scan the file in the first pass, you should count the number of integers instead of the number of characters.
when inserting, your loops are off by one: the tests should read while (L_move < index) and while (R_move >= index)
while (!feof(in)) is always wrong, you should instead write while (fscanf(in, "%d", &arr[n]) == 1) {...
you should probably allocate the arrays arr and sort_arr instead of defining them as VLAs with automatic storage to prevent undefined behavior on large input files.
you should use binary search into the sorted portion, otherwise your algorithm has a basic complexity of O(N2) that dwarfs the small gain obtained from the minimisation of the insertion phase.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
void print_array(const int arr[], int len) {
for (int j = 0; j < len; j++)
printf("%d%c", arr[j], " \n"[j == len - 1]);
}
int main(void) {
FILE *in;
int size_arr, n, start;
int value;
if ((in = fopen("data_a5.txt", "r")) == NULL) {
printf("Cannot open input file %s\n", "data_a5.txt");
exit(1);
}
for (size_arr = 0; fscanf(in, "%d", &value) == 1; size_arr++)
continue;
rewind(in);
int *arr = calloc(2 * size_arr + 1, sizeof(*arr));
if (arr == NULL) {
printf("Cannot allocate memory for %d entries\n", size_arr);
exit(1);
}
start = size_arr;
for (n = 0; n < size_arr && fscanf(in, "%d", &value) == 1; n++) {
/* insert value into the sorted array */
int a, b;
for (a = start, b = start + n; a < b;) {
int mid = a + (b - a) / 2;
if (arr[mid] < value) {
a = mid + 1;
} else {
b = mid;
}
}
/* insert value at offset b */
if (b - start < start + n - b) {
/* shift left portion to the left */
for (int i = start--; i < b; i++) {
arr[i - 1] = arr[i];
}
b--;
} else {
/* shift right portion to the right */
for (int i = start + n + 1; --i > b;) {
arr[i] = arr[i - 1];
}
}
arr[b] = value;
}
fclose(in);
print_array(arr + start, n);
free(arr);
return 0;
}
like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printArray(int arr[], int len){
while(len--)
printf("%d ", *arr++);
printf("\n");
}
int main(void){
int size_arr = 10;
int arr[size_arr];
int sort_arr[2 * size_arr + 1];
for(int i = 0; i < size_arr; ++i)
arr[i] = -50 + rand() % (100 + 1);
puts("before:");
printArray(arr, size_arr);
int left, right;
sort_arr[left = right = size_arr] = arr[0];
for (int n = 1; n < size_arr; ++n){
int v = arr[n];
if(v <= sort_arr[left]){
sort_arr[--left] = v;
} else if(v >= sort_arr[right]){
sort_arr[++right] = v;
} else {
int L = left, R = right, M, MV;
while(L <= R){
M = L + (R-L)/2;
MV = sort_arr[M];
if(MV < v)
L = M + 1;
else if(v < MV)
R = M - 1;
else
break;
}
//M: insert position
enum { LEFT, RIGHT } CHOICE;
if(v == MV){
int ML = M, MR = M;
while(sort_arr[ML-1] == sort_arr[ML])
--ML;
while(sort_arr[MR] == sort_arr[MR+1])
++MR;
if( ML-left >= right-MR){
M = MR+1;
CHOICE = RIGHT;
} else {
M = ML;
CHOICE = LEFT;
}
} else if(v > MV){
++M;
CHOICE = M-left+1 > right-M;// ? RIGHT : LEFT;
} else {
CHOICE = M-left-1 > right-M;// ? RIGHT : LEFT;
}
if(CHOICE == RIGHT){
memmove(sort_arr + M+1, sort_arr + M, (right-M+1)*sizeof(v));
sort_arr[M] = v;
++right;
} else {
memmove(sort_arr + left-1, sort_arr + left, (M-left)*sizeof(v));
sort_arr[M-1] = v;
--left;
}
}
}
puts("after:");
printArray(sort_arr + left, size_arr);
return 0;
}

How many anagrams there are in a sentence in C

I was asked to write a code that returns the maximum number of anagrams (word made by transposing the letters of another word like the word “secure” is an anagram of “rescue.”).
This is what I did:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char text[1000], angrm1[1000], angrm2[1000];
int i, j, k, count = 1, flag = 0, temp, size = 0, q = 1, counter = 0, max = 0;
char**point;
printf_s("Please enter the sentence, and then press Enter:\n");
gets(text);
strcpy_s(angrm1, 1000, text);
j = 1; i = 0;
for (i = 0; i < strlen(angrm1); i = k + 2) {
for (k = i; angrm1[k + 1] != ' '&&angrm1[k + 1]!=0; k++) {
if (angrm1[i] > angrm1[i + 1]) {
temp = angrm1[k];
angrm1[k] = angrm1[k + 1];
angrm1[k + 1] = temp;
}
}
Blockquote Arrange the words
size = strlen(angrm1);
}
for (i = 0; angrm1[i] != 0; i++)
{
if (angrm1[i] == ' ')
{
angrm1[i] = 0;
count++;
}
}
point = (char*)malloc(sizeof(char)*count);
for (i = 0; i < (size - 1); i++)
{
if (angrm1[i] == 0)
{
point[q] = &point[i + 1];
q++;
}
}
for (i = 0; i < counter; i++)
{
for (q = i + 1; q < counter; q++)
{
if (point[q] == 0 || point[i] == 0)
continue;
if (!strcmp(point[q], point[i]))
{
counter++;
point[q] = 0;
}
}
if (max < counter)
max = counter;
counter = 0;
}
printf_s("The maximum (not yet) number of anagram words in this sentence is %d", &max);
}
The first part works (in my opinion).
But when I check with the debugger, it skips the loop and I get junk.
Can someone please help me by pointing to the problem, and explaining how to fix it?

Adding decimal numbers as strings in C

So I understand how to perform calculations on integers represented in strings and then printing the result in a string. But I'm lost on how to do the same thing with a decimal in the number represented in a string.
Here's how I did it with integers. This part of the code is adding together two integers:
int answer = 0;
char str1[100];
int count = 0;
int total = 0;
int k = 0;
int diff = 0;
if (ele == ele2) {
for (k = strlen(op1) - 1; k > -1; k--) {
if ((strspn(operand, "+") == strlen(operand))) {
answer = (op1[k] - '0') + (op2[k] - '0');
} else if ((strspn(operand, "-") == strlen(operand))) {
answer = (op1[k] - '0') - (op2[k] - '0');
}
total += (pow(10, count) * answer);
count++;
}
sprintf(str1, "%d", total);
printf("Answer: %s ", str1);
}
Output
// 12 + 14
Answer: 26 // Answer given as a string
Example
12.2 + 14.5 // Three strings
Answer: 16.7 // Answer as string
Current Attempt:
for (k = strlen(argv[1]) - 1; k > -1; k--) {
if (argv[1][k] == '.') {
dec = k;
} else {
answer = (argv[1][k] - '0') + (argv[3][k] - '0');
total += (pow(10, count) * answer);
count++;
}
}
// needs to be converted to a long?
// ele is the length of the operand
total = total / pow(10, ele - dec);
sprintf(str1, "%d", total);
printf("Answer: %s ", str1);
Sharing a simple algo to begin with (and assuming your adding integer funciton works fine).
A decimal number is basically two integers separated by ".".
Identify the position of "." and grab the two sides of the integer as integerPart, decimalPart
One caveat on getting the decimalPart is that the length of all the decimalParts should be same, if not, add "0"s in the suffix.
Add the integerPart, add the decimalPart and handle the carryForwards in the decimalPart.
So,
12.2 + 14.95
= (12 + 14) (20 + 95)
= 26 115
= 26+1 15
= 27.15
This is a quick and dirty implementation: no parameter check, no deep test only an idea of how you should process.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int total_digits;;
int decimal_points;
int *number;
} NUMBER, *DECIMALNUMBER;
DECIMALNUMBER initilize(char *str)
{
DECIMALNUMBER result = calloc(1, sizeof(NUMBER));
int in_decimal = 0;
char *s;
int i;
for (s = str; *s; s++)
{
if (isdigit(*s))
{
result->total_digits++;
if (in_decimal)
{
result -> decimal_points++;
}
}
else if (*s == '.')
{
in_decimal = 1;
}
else
{
return NULL;
}
}
result->number = calloc(result->decimal_points, sizeof(int));
i=0;
for (s = str; *s; s++)
{
if (isdigit(*s))
{
result->number[i++] = (int)(*s - '0');
}
}
// printf("result->total_digits is %d\n",result->total_digits);
// printf("result->decimal_points is %d\n",result->decimal_points);
// printf("result is %d\n",result->number[--i]);
// printf("result is %d\n",result->number[--i]);
// printf("result is %d\n",result->number[--i]);
return result;
}
void print_number(DECIMALNUMBER p)
{
int i;
for (i=0; i<p->total_digits; i++)
{
if (i==p->total_digits - p->decimal_points) {
printf(".");
}
printf("%d", p->number[i]);
}
printf("\n");
}
DECIMALNUMBER sum(DECIMALNUMBER a, DECIMALNUMBER b)
{
int max_decimals = a->decimal_points>b->decimal_points ? a->decimal_points : b->decimal_points;
int max_digits_count = a->total_digits>b->total_digits ? a->total_digits : b->total_digits;
DECIMALNUMBER result = calloc(1, sizeof(NUMBER));
result->total_digits = max_digits_count;
result->decimal_points = max_decimals;
result->number = calloc(max_digits_count, sizeof(int));
int i1 = a->total_digits-1;
int i2 = b->total_digits-1;
int i3 = result->total_digits-1;
int remainder = 0;
int summed;
while (i1 >= 0 || i2 >=0)
{
int aa = i1 < 0 ? 0 : a->number[i1];
int bb = i2 < 0 ? 0 : b->number[i2];
summed = aa + bb + remainder;
result->number[i3] = summed % 10;
remainder = summed / 10;
i1--;
i2--;
i3--;
}
return result;
}
int main()
{
DECIMALNUMBER a = initilize("12.2");
DECIMALNUMBER b = initilize("16.7");
print_number(a);
print_number(b);
DECIMALNUMBER c = sum (a,b);
print_number(c);
return 0;
}

Resources