Thread: Need help with Realloc()

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    12

    Need help with Realloc()

    Spec:
    Create a program that reads from a file and converts strings to integers (using a struct). Then add and subtract them.

    Question/Problem:
    I'm working on the adding function. I noticed that for numbers that add up and exceed the struct integer array (ie. sum->digits is an array in a struct). For example 55 + 55 = 110 (3 digits in a 2 digit array). So, what I'm trying to do is use Realloc() operator/function to extend the array in a struct by one more digit to store the carry over from the addition. The program fails when it runs the Realloc().

    Code:
    /*
    * Peter Nguyen
    * COP 3502C - 0001
    * Program 1 - BigIntegers
    * 01/27/10
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct integer {
    	int* digits;
    	int size;
    };
    
    struct integer* convert_integer(char* stringInt);
    void print(struct integer *p);
    struct integer* add(struct integer *p, struct integer *q);
    struct integer* subtract(struct integer *p, struct integer *q);
    int compare(struct integer *p, struct integer *q);
    
    int main (void)
    {
    	int numOflines; // Number of lines in "bigint.txt" file
    	int i = 0, 
    		j = 0;
    	int operator = 0;
    	char string[201]; // Store string
    	struct integer *num1,
    		*num2,
    		*answer; 
    
    	// Open "bigint.txt" file
    	FILE * myFile;
    	myFile = fopen("bigint.txt", "r");
    
    	// Reads number of operations
    	fscanf(myFile, "%d", &numOflines); 
    
    	// Run loop for the number of operations
    	for(i = 0; i < numOflines; i++)
    	{
    		// Read operator (1 = addition and 2 = subtraction)
    		fscanf(myFile, "%d", &operator);
    
    		// Read line and store the two strings
    		fscanf(myFile, "%s", &string);
    		num1 = convert_integer(string);
    		fscanf(myFile, "%s", &string);			
    		num2 = convert_integer(string);
    
    		print(num1);
    		print(num2);
    
    		if(operator == 1)
    		{
    			answer = add(num1, num2);
    			print(answer);
    		}
    		// subtract function not written yet
    		/*	else if (operator == 2)
    		answer = subtract(num1, num2);
    		else
    		// If operator is not + or -
    		printf("The wrong operator!"\n);
    		*/
    		free(num1->digits);
    		free(num1);
    		free(num2->digits);
    		free(num2);
    		free(answer->digits);
    		free(answer);
    
    	}
    
    	return 0;
    
    	system("pause");
    }
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: the first parameter is string that stores         //
    //               only contains digits, doesn't start with	       //
    //               0, and is 200 or fewer characters long.	       //
    //Postconditions: The function will read the digits of the	       //
    //	          large integer character by character, 	           //
    //	          convert them into integers and return a 	           //
    //                pointer to the appropriate struct integer.	   //
    /////////////////////////////////////////////////////////////////////
    struct integer* convert_integer(char* stringInt)
    {
    
    	int i,
    		j = 0;
    	struct integer *p = (struct integer*)(malloc(sizeof(struct integer)));
    
    	// Allocate memory		
    	p->size = strlen(stringInt);
    	p->digits = (int *)(malloc(sizeof(int)*p->size));
    
    	// Reverse the order
    	for(i = p->size - 1; i >= 0; i--, j++)
    		p->digits[i] = (int)(stringInt[j] - '0');
    
    	return p;
    
    }
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: p is a pointer to a big integer.		           //
    //Postconditions: The big integer pointed to by p is 		       //
    //                printed out.					                   //
    /////////////////////////////////////////////////////////////////////
    void print(struct integer *p)
    {
    	int i;
    
    	for(i = p->size - 1; i >= 0; i--)
    		printf("%d", p->digits[i]);
    	printf("\n");
    }
    
    /////////////////////////////////////////////////////////////////////
    //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.					                       //
    /////////////////////////////////////////////////////////////////////
    struct integer* add(struct integer *p, struct integer *q)
    {
    	struct integer *sum = (struct integer*)(malloc(sizeof(struct integer)));
    	int i,
    		num1,
    		num2,
    		carry = 0;
    
    	sum->digits = (int*)(malloc(sizeof(int)*sum->size));
    
    	if(p->size > q->size)
    		sum->size = p->size;
    	else
    		sum->size = q->size;
    
    	for(i = 0; i <= sum->size; i++)
    	{
    		if(p->digits[i] == '\0')
    			num1 = 0;
    		else
    		{
    			num1 = p->digits[i];
    
    			if(q->digits[i] == '\0')
    				num2 = 0;
    			else
    				num2 = p->digits[i];
    
    			if(i == sum->size && carry == 1)
    			{
    				sum->digits = (int*)realloc(sum->digits, (sum->size*sizeof(int)));
    				num1 = 0;
    				num2 = 0;
    			}
    
    			sum->digits[i] = num1 + num2 + carry;
    
    			if(sum->digits[i] >= 10)
    			{
    				sum->digits[i] -= 10;
    				carry = 1;
    			}
    			else
    				carry = 0;
    		}
    
    		return sum;
    	}
    
    	/////////////////////////////////////////////////////////////////////
    	//Preconditions: p and q are pointers to struct integers.	       //
    	//Postconditions: A new struct integer is created that 		       //
    	//                stores the absolute value of the 		           //
    	//                difference between the two and a pointer 	       //
    	//                to this is returned.				               // 
    	/////////////////////////////////////////////////////////////////////
    	struct integer* subtract(struct integer *p, struct integer *q)
    	{
    		return 0;
    	}
    
    	/////////////////////////////////////////////////////////////////////
    	//Preconditions: Both parameters of the function are 		       //
    	//	  pointers to struct integer. 				                   //
    	//Postconditions: The function compares the digits of two 	       //
    	//	numbers and returns: 					                       // 
    	//    -1 if the first number is smaller than the second,	       // 
    	//     0 if the first number is equal to the second number,	       //
    	//   1 if the first number is greater than the second.  	       //
    	/////////////////////////////////////////////////////////////////////   
    	int compare(struct integer *p, struct integer *q)
    	{
    		return 0;
    	}

  2. #2
    Registered User
    Join Date
    Jan 2010
    Posts
    1
    I ran your program, I haven't been able to figure out the relloc yet, but it told me you had an error in the add function. You're missing a "}" at the end of it, you can put it right after the "return sum;". Just a little heads up. I'll see what I can do about the relloc

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    12
    I fixed some mistakes in the program above, but I'm still having trouble with using realloc().

    Also any suggestions on making more compare statement more detailed. As it stands now I can't really integrate it into the subtraction function just yet. I can't figure out how to fully compare to see if num1 is a larger number than num2. I can figure out how to compare the two in terms of length size.


    Code:
    /*
    * Peter Nguyen
    * COP 3502C - 0001
    * Program 1 - BigIntegers
    * 01/27/10
    */
    
    /*
    NOTES:
    1 ) Program can successfully add and subtract. If the last digit isn't a carry over number and both are equal length numbers.
    2 ) Program crashes if last number to be inputed is a carry over number.
    3 ) Program can't handle a longer lenth number being subtracted by a smaller length number.
    4 ) Compare function isn't in depth enough to be integrated into subtraction fuction yet.
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct integer {
    	int* digits;
    	int size;
    };
    
    struct integer* convert_integer(char* stringInt);
    void print(struct integer *p);
    struct integer* add(struct integer *p, struct integer *q);
    struct integer* subtract(struct integer *p, struct integer *q);
    int compare(struct integer *p, struct integer *q);
    
    int main (void)
    {
    	// Number of lines in "bigint.txt" file
    	int numOflines;
    	int i = 0;
    	int oper = 0;
    	char string[201];
    	struct integer *num1,
    		*num2,
    		*answer; 
    
    	// Open "bigint.txt" file
    	FILE * myFile;
    	myFile = fopen("bigint.txt", "r");
    
    	// Reads number of operations
    	fscanf(myFile, "%d", &numOflines); 
    
    	// Run loop for the number of operations
    	for(i = 0; i < numOflines; i++)
    	{
    		// Read operator (1 = addition and 2 = subtraction)
    		fscanf(myFile, "%d", &oper);
    
    		// Read line and store the two strings
    		fscanf(myFile, "%s", &string);
    		num1 = convert_integer(string);
    		fscanf(myFile, "%s", &string);			
    		num2 = convert_integer(string);
    
    		// Addition
    		if(oper == 1)
    		{
    			answer = add(num1, num2);
    			print(num1);
    			printf(" + ");
    			print(num2);
    			printf(" = ");
    			print(answer);
    			printf("\n\n");
    		}
    		// Subtraction
    		else if(oper == 2)
    		{
    			answer = subtract(num1, num2);
    			print(num1);
    			printf(" - ");
    			print(num2);
    			printf(" = ");
    			print(answer);
    			printf("\n\n");
    		}
    		// If operator is not + or -
    		else if(oper != 1 && oper != 2)
    			printf("The wrong operator!\n");
    
    		// Free memory
    		free(num1->digits);
    		free(num1);
    		free(num2->digits);
    		free(num2);
    		//free(answer->digits);  // This crashes the program
    		//free(answer);			 // This crashes the program
    	}
    	system("pause");
    	return 0;
    }
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: the first parameter is string that stores         //
    //               only contains digits, doesn't start with	       //
    //               0, and is 200 or fewer characters long.	       //
    //Postconditions: The function will read the digits of the	       //
    //	          large integer character by character, 	           //
    //	          convert them into integers and return a 	           //
    //                pointer to the appropriate struct integer.	   //
    /////////////////////////////////////////////////////////////////////
    struct integer* convert_integer(char* stringInt)
    {
    	int i,
    		j = 0;
    	struct integer *p = (struct integer*)(malloc(sizeof(struct integer)));
    
    	// Allocate memory		
    	p->size = strlen(stringInt);
    	p->digits = (int *)(malloc(sizeof(int)*p->size));
    
    	// Reverse the order
    	for(i = p->size - 1; i >= 0; i--, j++)
    		p->digits[i] = (int)(stringInt[j] - '0');
    
    	return p;
    }
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: p is a pointer to a big integer.		           //
    //Postconditions: The big integer pointed to by p is 		       //
    //                printed out.					                   //
    /////////////////////////////////////////////////////////////////////
    void print(struct integer *p)
    {
    	int i;
    	// Print backwards (correctly)
    	for(i = p->size - 1; i >= 0; i--)
    		printf("%d", p->digits[i]);
    }
    
    /////////////////////////////////////////////////////////////////////
    //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.					                       //
    /////////////////////////////////////////////////////////////////////
    struct integer* add(struct integer *p, struct integer *q)
    {
    	// Allocate memory for struct
    	struct integer *sum = (struct integer*)(malloc(sizeof(struct integer)));
    	int i,
    		num1,
    		num2,
    		carry = 0;
    
    	// Find larger number
    	if(p->size > q->size)
    		sum->size = p->size;
    	else
    		sum->size = q->size;
    	// Allocate memory for digits
    	sum->digits = (int*)(malloc(sizeof(int)*sum->size));
    
    	for(i = 0; i <= sum->size; i++)
    	{
    		// Set digit to int
    		num1 = p->digits[i];
    		num2 = q->digits[i];
    
    		// Setup for if there is a carry over at the end
    		if(i == sum->size && carry == 1)
    		{
    			// Expand digits to fit last carry over
    			sum->digits = (int*)realloc(sum->digits+1, sizeof(int)); // Not sure if its setup correctly
    			// Set numbers to 0, because it's filled with garage
    			num1 = 0; 
    			num2 = 0;
    		}
    		// Adding
    		sum->digits[i] = num1 + num2 + carry;
    		// Carry over process
    		if(sum->digits[i] >= 10)
    		{
    			sum->digits[i] -= 10;
    			carry = 1;
    		}
    		else
    			carry = 0;
    	}
    	return sum;
    }
    
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: p and q are pointers to struct integers.	       //
    //Postconditions: A new struct integer is created that 		       //
    //                stores the absolute value of the 		           //
    //                difference between the two and a pointer 	       //
    //                to this is returned.				               // 
    /////////////////////////////////////////////////////////////////////
    struct integer* subtract(struct integer *p, struct integer *q)
    {
    	// Allocate memory
    	struct integer *diff = (struct integer*)(malloc(sizeof(struct integer)));
    	int i,
    		num1,
    		num2,
    		test;
    
    	// Find longer number
    	if(p->size > q->size)
    		diff->size = p->size;
    	else
    		diff->size = q->size;
    	
    	// Comapre numbers
    	test = compare(p, q); // Needs some work so I can integrate with difference
    	
    	// Allocate memory
    	diff->digits = (int*)(malloc(sizeof(int)*diff->size));
    
    	for(i = 0; i <= diff->size; i++)
    	{
    		num1 = p->digits[i];
    		num2 = q->digits[i];
    
    		// Carry over process
    		if(num1 < num2)
    		{
    			p->digits[i+1] -= 1;
    			num1 += 10;
    		}
    		// Difference
    		diff->digits[i] = num1 - num2;
    	}
    	return diff;
    }
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: Both parameters of the function are 		       //
    //	  pointers to struct integer. 				                   //
    //Postconditions: The function compares the digits of two 	       //
    //	numbers and returns: 					                       //
    //    -1 if the first number is smaller than the second,	       //
    //     0 if the first number is equal to the second number,	       //
    //   1 if the first number is greater than the second.  	       //
    /////////////////////////////////////////////////////////////////////   
    int compare(struct integer *p, struct integer *q)
    {
    	int i,
    		num1 = 0,
    		num2 = 0;
    
    	// Still need to figure how to make it more in depth
    	for(i = p->size - 1; i >= 0; i--)
    	{
    		if(p->digits[i] > q->digits[i])
    		{
    			if(p->size > q->size)
    				return 1;
    		}
    		if(p->digits[i] < q->digits[i])
    		{
    			if(p->size < q->size)
    				return -1;
    		}
    		if(p->digits[i] == q->digits[i] && p->size == q->size)
    			return 0;
    	}
    }
    Last edited by krazyxazn; 01-26-2010 at 04:35 PM.

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Seems like your making a *lot* of work here that really isn't necessary.

    I'd recommend:

    Taking in your digits, right into one of the two char array's. You'll change them from char values to numeral values by subtracting each '0' from each char.

    If your strings have a newline included with them, remove it with a while loop. Leave the end of string char, in place.

    Now go to the function that will perform the computation. Since char's are just small numbers, and all your digits are small numbers, just do the arithmetic, using the regular way you learned in elementary school.

    You can use the strlen() function to see which "number" is the larger, (that's why you left the end of string char in place), but obviously you don't include that '\0' char, into any of your arithmetic computations.

    You don't need any structs, and you don't need all this &^%$# code. Simple, short, and easy. There's no need to realloc, anything, imo.

  5. #5
    Registered User
    Join Date
    Mar 2009
    Posts
    12
    Quote Originally Posted by Adak View Post
    Seems like your making a *lot* of work here that really isn't necessary.

    I'd recommend:

    Taking in your digits, right into one of the two char array's. You'll change them from char values to numeral values by subtracting each '0' from each char.

    If your strings have a newline included with them, remove it with a while loop. Leave the end of string char, in place.

    Now go to the function that will perform the computation. Since char's are just small numbers, and all your digits are small numbers, just do the arithmetic, using the regular way you learned in elementary school.

    You can use the strlen() function to see which "number" is the larger, (that's why you left the end of string char in place), but obviously you don't include that '\0' char, into any of your arithmetic computations.

    You don't need any structs, and you don't need all this &^%$# code. Simple, short, and easy. There's no need to realloc, anything, imo.
    Unfortunately this assignment requires the user to store them in structs . Thanks for the other tips.

  6. #6
    Registered User
    Join Date
    Mar 2009
    Posts
    12
    I solved how to add/subtract different length numbers and numbers that extend the array.

    Well, when you sometimes fix problems you create new ones .
    8888888888 + 2222222222 = 11111111110

    9999999999 - 10000000000 = 09999999999

    0-1-1-1-1-1-1-1-1-10 - 9999999999 = 00000000001

    Press any key to continue . . .
    I still need to figure out how to make the Compare function setup correctly. Also how do I use the return #; from the Compare function to make an IF Statement in my Subtraction Function?

    Ex.
    int compare(){
    if(p->digits[i] > q->digits[i] && p->size > q->size)
    return 1;
    }

    int subtraction(){
    compare (num1, num2);
    if ( something ){
    something;
    }
    Code:
    /*
    * Peter Nguyen
    * COP 3502C - 0001
    * Program 1 - BigIntegers
    * 01/27/10
    */
    
    /*
    NOTES:
    1 ) Program can successfully add and subtract. If the last digit isn't a carry over number.
    2 ) Program crashes if last number to be inputed is a carry over number.
    3 ) Compare function isn't in depth enough to be integrated into subtraction craption yet.
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct integer {
    	int* digits;
    	int size;
    };
    
    struct integer* convert_integer(char* stringInt);
    void print(struct integer *p);
    struct integer* add(struct integer *p, struct integer *q);
    struct integer* subtract(struct integer *p, struct integer *q);
    int compare(struct integer *p, struct integer *q);
    
    int main (void)
    {
    	// Number of lines in "bigint.txt" file
    	int numOflines;
    	int i = 0;
    	int oper = 0;
    	char string[201];
    	struct integer *num1,
    		*num2,
    		*answer; 
    
    	// Open "bigint.txt" file
    	FILE * myFile;
    	myFile = fopen("bigint.txt", "r");
    
    	// Reads number of operations
    	fscanf(myFile, "%d", &numOflines); 
    
    	// Run loop for the number of operations
    	for(i = 0; i < numOflines; i++)
    	{
    		// Read operator (1 = addition and 2 = subtraction)
    		fscanf(myFile, "%d", &oper);
    
    		// Read line and store the two strings
    		fscanf(myFile, "%s", &string);
    		num1 = convert_integer(string);
    		fscanf(myFile, "%s", &string);			
    		num2 = convert_integer(string);
    
    		// Addition
    		if(oper == 1)
    		{
    			answer = add(num1, num2);
    			print(num1);
    			printf(" + ");
    			print(num2);
    			printf(" = ");
    			print(answer);
    			printf("\n\n");
    		}
    		// Subtraction
    		else if(oper == 2)
    		{
    			answer = subtract(num1, num2);
    			print(num1);
    			printf(" - ");
    			print(num2);
    			printf(" = ");
    			print(answer);
    			printf("\n\n");
    		}
    		// If operator is not + or -
    		else if(oper != 1 && oper != 2)
    			printf("The wrong operator!\n");
    
    		// Free memory
    		free(num1->digits);
    		free(num1);
    		free(num2->digits);
    		free(num2);
    		//free(answer->digits);  // This crashes the program
    		//free(answer);			 // This crashes the program
    	}
    	system("pause");
    	return 0;
    }
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: the first parameter is string that stores         //
    //               only contains digits, doesn't start with	       //
    //               0, and is 200 or fewer characters long.	       //
    //Postconditions: The function will read the digits of the	       //
    //	          large integer character by character, 	           //
    //	          convert them into integers and return a 	           //
    //                pointer to the appropriate struct integer.	   //
    /////////////////////////////////////////////////////////////////////
    struct integer* convert_integer(char* stringInt)
    {
    	int i,
    		j = 0;
    	struct integer *p = (struct integer*)(malloc(sizeof(struct integer)));
    
    	// Allocate memory		
    	p->size = strlen(stringInt);
    	p->digits = (int *)(malloc(sizeof(int)*p->size));
    
    	// Reverse the order
    	for(i = p->size - 1; i >= 0; i--, j++)
    		p->digits[i] = (int)(stringInt[j] - '0');
    
    	return p;
    }
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: p is a pointer to a big integer.		           //
    //Postconditions: The big integer pointed to by p is 		       //
    //                printed out.					                   //
    /////////////////////////////////////////////////////////////////////
    void print(struct integer *p)
    {
    	int i;
    	// Print backwards (correctly)
    	for(i = p->size - 1; i >= 0; i--)
    		printf("%d", p->digits[i]);
    }
    
    /////////////////////////////////////////////////////////////////////
    //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.					                       //
    /////////////////////////////////////////////////////////////////////
    struct integer* add(struct integer *p, struct integer *q)
    {
    	// Allocate memory for struct
    	struct integer *sum = (struct integer*)(malloc(sizeof(struct integer)));
    	int i,
    		num1,
    		num2,
    		carry = 0,
    		j,
    		n;
    
    	// Find larger number
    	if(p->size > q->size)
    	{
    		sum->size = p->size + 1;
    		j = q->size;
    		n = 0;
    	}
    	else
    	{
    		sum->size = q->size + 1;
    		j = p->size;
    		n = 1;
    	}
    	// Allocate memory for digits
    	sum->digits = (int*)(malloc(sizeof(int)*sum->size));
    
    	for(i = 0; i < j; i++)
    	{
    		// Set digit to int
    		num1 = p->digits[i];
    		num2 = q->digits[i];
    
    		// Adding
    		sum->digits[i] = num1 + num2 + carry;
    
    		// Carry over process
    		if(sum->digits[i] >= 10)
    		{
    			sum->digits[i] -= 10;
    			carry = 1;
    		}
    		else
    			carry = 0;
    	}
    
    	for(i = i; i < sum->size; i ++)
    	{
    		// Set digit to int
    		num1 = p->digits[i];
    		num2 = q->digits[i];
    
    		// Input zeros for shorter numbers
    		if(n == 0)
    		{
    			num2 = 0;
    			if(i == sum->size - 1)
    				num1 = 0;
    		}
    		if(n == 1)
    		{
    			num1 = 0;
    			if(i == sum->size - 1)
    				num2 = 0;
    		}
    		// Adding
    		sum->digits[i] = num1 + num2 + carry;
    
    		// Carry over process
    		if(sum->digits[i] >= 10)
    		{
    			sum->digits[i] -= 10;
    			carry = 1;
    		}
    		else
    			carry = 0;
    	}
    	return sum;
    }
    
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: p and q are pointers to struct integers.	       //
    //Postconditions: A new struct integer is created that 		       //
    //                stores the absolute value of the 		           //
    //                difference between the two and a pointer 	       //
    //                to this is returned.				               // 
    /////////////////////////////////////////////////////////////////////
    struct integer* subtract(struct integer *p, struct integer *q)
    {
    	// Allocate memory
    	struct integer *diff = (struct integer*)(malloc(sizeof(struct integer)));
    	int i,
    		num1,
    		num2,
    		test,
    		j,
    		n;
    
    	// Find longer number
    	if(p->size > q->size)
    	{
    		diff->size = p->size;
    		j = q->size;
    		n = 0;
    	}
    	else
    	{
    		diff->size = q->size;
    		j = p->size;
    		n = 1;
    	}
    
    	// Comapre numbers
    	test = compare(p, q); // Needs some work so I can integrate with difference
    
    	// Allocate memory
    	diff->digits = (int*)(malloc(sizeof(int)*diff->size));
    
    	for(i = 0; i < j; i++)
    	{
    		num1 = p->digits[i];
    		num2 = q->digits[i];
    
    		// Carry over process
    		if(num1 < num2)
    		{
    			p->digits[i+1] -= 1;
    			num1 += 10;
    		}
    		// Difference
    		diff->digits[i] = num1 - num2;
    	}
    
    	for(i = i; i < diff->size; i ++)
    	{
    		// Set digit to int
    		num1 = p->digits[i];
    		num2 = q->digits[i];
    
    		// Input zeros for shorter numbers
    		if(n == 0)
    		{
    			num2 = 0;
    			if(i == diff->size - 1)
    				num1 = 0;
    		}
    		if(n == 1)
    		{
    			num1 = 0;
    			if(i == diff->size - 1)
    				num2 = 0;
    		}
    
    		// Adding
    		diff->digits[i] = num1 + num2;
    	}
    
    	return diff;
    }
    
    /////////////////////////////////////////////////////////////////////
    //Preconditions: Both parameters of the function are 		       //
    //	  pointers to struct integer. 				                   //
    //Postconditions: The function compares the digits of two 	       //
    //	numbers and returns: 					                       //
    //    -1 if the first number is smaller than the second,	       //
    //     0 if the first number is equal to the second number,	       //
    //   1 if the first number is greater than the second.  	       //
    /////////////////////////////////////////////////////////////////////   
    int compare(struct integer *p, struct integer *q)
    {
    	int i,
    		num1 = 0,
    		num2 = 0;
    
    	// Still need to figure how to make it more in depth
    	for(i = p->size - 1; i >= 0; i--)
    	{
    		if(p->digits[i] > q->digits[i] && p->size > q->size)
    			return 1;
    		if(p->digits[i] < q->digits[i] && p->size < q->size)
    			return -1;
    		if(p->digits[i] == q->digits[i] && p->size == q->size)
    			return 0;
    	}
    }
    Last edited by krazyxazn; 01-27-2010 at 02:44 PM.

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by krazyxazn View Post
    Also a quick question. How do I read in a return 1, return 0, return -1, and etc, so I can use it to write in an IF statement?
    Do you mean like:
    Code:
    int r = compare(....
    if (r>0) {....
    else if (r<0) {...
    else {...
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I don't know how to integrate it into your program, but this appears to work fine:

    Where the digits are being stored in the char arrays str1[] and str2[]. It moves the larger
    number, into str1[], and the smaller into str2[].

    Code:
        str1len = strlen(str1);		//get it's length
        str2len = strlen(str2);
        if(str1len < str2len) {
          strcpy(answer, str1);
          strcpy(str1, str2);
          strcpy(str2, answer);
          j = str1len;
          str1len = str2len;
          str2len = j;
        }
        if(str1len == str2len) {
          if((strcmp(str1, str2)) < 0) {
            strcpy(answer, str1);
            strcpy(str1, str2);
            strcpy(str2, answer);
          }
        }

  9. #9
    Registered User
    Join Date
    Mar 2009
    Posts
    12
    Quote Originally Posted by MK27 View Post
    Do you mean like:
    Code:
    int r = compare(....
    Thanks, it's been a year since I took C programming. So I've forgotten some of the basics.

    variable = compare (...); Exactly what I was looking for.

    @ Adak: Thanks, I'll give that a try.

  10. #10
    Registered User
    Join Date
    Mar 2009
    Posts
    12
    Thanks for the help Adak, the code worked perfectly, but something is up with my code when it prints out. So I'll just leave my compare function the way it is and just not call it . He never said we had to use it .

    Now I got a few more hours to figure out how to properly print out the code.

    INPUT
    2
    2 9999999999 10000000000
    2 10000000000 9999999999
    OUTPUT
    0-1-1-1-1-1-1-1-1-10 - 9999999999 = 00000000001
    0-1-1-1-1-1-1-1-1-10 - 9999999999 = 00000000001
    I tried replacing the part of the code that adds in the zeros to take over blank spaces of uneven arrays with NULLs instead of zeros, but the leading zeros will still show up.

  11. #11
    Registered User
    Join Date
    Mar 2009
    Posts
    12
    Someone sent me this bit of code for the leading zeros removal, but it doesn't work. It looks like it would though with some editing.

    Code:
    int resultsize = result->size;  // This sets the new temp length to the current length
    int leading_zero = 1; 
    int* tmp;
    
    while(resultsize && leading_zero)
    {	
    	if(result->digits[resultsize - 1] == 0)		// It seems to skip over this even though the last digit is indeed a zero
    		resultsize--;	// Goes backwards from the first digit (which is the last in the array; stored backwards)
    	else		
    		leading_zero = 0; // stops if leading_digit isn't zero
    }
    
    if(resultsize != result->size)
    {	
    	tmp = result->digits;	// Store digits
    	result->digits = malloc(sizeof(int)*resultsize);	// alloc result->digits to the new size without leading zeros
    	memcpy(result->digits, tmp, resultsize*sizeof(int));	// paste in data to result->digits
    	result->size = resultsize;	// paste in new size
    	free(tmp);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. did i understood right this explantion of realloc..
    By transgalactic2 in forum C Programming
    Replies: 3
    Last Post: 10-24-2008, 07:26 AM
  2. writing a pack-style function, any advices?
    By isaac_s in forum C Programming
    Replies: 10
    Last Post: 07-08-2006, 08:09 PM
  3. using realloc
    By bobthebullet990 in forum C Programming
    Replies: 14
    Last Post: 12-06-2005, 05:00 PM
  4. segfault on realloc
    By ziel in forum C Programming
    Replies: 5
    Last Post: 03-16-2003, 04:40 PM
  5. realloc realloc realloc
    By Linette in forum C++ Programming
    Replies: 4
    Last Post: 01-19-2002, 09:18 PM