i need to make my array smaller to save memory and for some reason my program crashes when i call the print function i made to read out the numbers in the aray. i cant seem to find out why this only happens with the larger number because it works for making the array one size smaller just not 4 in the test I'm doing. when i do the test for re sizing 4 smaller it seems like it never saves the array because i put the print function be the realloc and it still crashes. also when i run the program with out pauses it crashes it would be nice to know why it did that too (same function)
here is the function
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
/******code******/
////////////////////////////////////////////////////////////////////////////////
//Preconditions: p and q are pointers to struct integers.
//
//Postconditions: A new struct integer is created that
// stores the sum of the integers pointed to
// by p and q and a pointer to it is
// returned.
//
//Description:
////////////////////////////////////////////////////////////////////////////////
struct integer* add(struct integer *p, struct integer *q)
{
struct integer* big_number;
int carry = 0;
int test;
int largest;
int i;
int j = 0;
test = compare(p, q);
if(test == 1)
{
largest = p->size;
}
else
{
largest = q->size;
}
big_number = malloc(sizeof(struct integer));
big_number->digits = malloc(largest + 1 * sizeof(int));
for(i = 0; i == largest; i++)
{
big_number->digits[i] = 0;
}
for(i = 0; i < largest +1; i++)
{
if(p->size <= i && q->size <= i)
{
big_number->digits[i] = carry;
carry = 0;
break;
}
else if(p->size <= i)
{
big_number->digits[i] = q->digits[i] + carry;
carry = 0;
}
else if(q->size <= i)
{
printf("**test** i=%d", i);
big_number->digits[i] = p->digits[i] + carry;
carry = 0;
}
else
{
big_number->digits[i] = p->digits[i] + q->digits[i] +carry;
if(big_number->digits[i] > 9)
{
big_number->digits[i] -= 10;
carry = 1;
}
else
{
carry = 0;
}
}
system("pause");
//i have to put a pause here or the program will crash with no error message
}
for(i = largest, j = 0; big_number->digits[i] == 0 && i > 0; i--, j++);
big_number->digits = (int*)realloc(big_number->digits,(largest-j) * sizeof(int));
big_number->size = largest - j + 1;
//the program crashes here with a windows message saying it "needs to close"
print(big_number);
return big_number;
}
////////////////////////////////////////////////////////////////////////////////
//Preconditions: p is a pointer to a big integer.
//
//Postconditions: The big integer pointed to by p is
// printed out.
//
//Description:
////////////////////////////////////////////////////////////////////////////////
void print(struct integer *p)
{
int i;
for(i = p->size -1 ; i >= 0; i--)
{
printf("%d", p->digits[i]);
}
printf("\n");
}