使用char添加大数字并返回值。指针错误

时间:2013-10-28 03:42:16

标签: c pointers

嘿伙计们我的程序任务要求我编写一个程序来添加大数字并通过调用函数返回它。我很难理解如何将值返回显示。我相信我的错误是在我对指针的错误使用中,但我不明白它是否足以弄明白。请帮忙!

我在问题所在的行旁边放了一个箭头,但我不知道如何解决它。 谢谢!

以下是代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *addlarge(char, char, char); <--


int main(int argc, char* argv[])
{
unsigned char number1 [256] = {'0'};
unsigned char number2 [256] = {'0'};
unsigned char result [256] = {0};

//ask for numbers
printf ("Please enter a number upto 255 digits long:\n");
scanf ("%s", number1);
printf ("Please enter another number upto 255 digits long:\n");
scanf ("%s", number2);
char *result1 = addLarge(*number1, *number2, *result); <--
printf("\nThe sum is %s\n", result1); <--
}

char *addLarge(char *number1, char *number2, char *result) <--
{
    int x, z, b, padding1, padding2, padding, y=0, sum, carry=0;

//right aligns the numbers
    x = strlen(number1);
    padding1 = 255 - x;
    memmove(number1+padding1,number1,x);
    memset(number1, 0, padding1);

    z = strlen(number2);
    padding2 = 255 - z;
    memmove(number2+padding2,number2,z);
    memset(number2, 0, padding2);

//works it out
    for(y=254; y>=0; y--) {
    if ( (number1[y] != 0) || (number2[y] != 0) ) {
        if ( (number1[y] != 0) && (number2[y] != 0) ) {
        sum = 0;
        sum += carry;
        carry = 0;
        sum += number1[y] - '0' + number2[y] - '0';
        carry = sum / 10;
        result[y+1] = sum % 10 + '0';
        }
    else {
    sum = 0;
    sum += carry;
    carry = 0;
    sum += number1[y] - '0' + number2[y];
    carry = sum / 10;
    result[y+1] = sum % 10 + '0';
    }
}

//adds the carries
if ((number1[y] == 0) && (number2[y] == 0) && (carry==1)){
        result[y+1] = 1 + '0';
        carry = 0;
    }
}

//shifts number back
    for (b=255; result[b] != 0; b--){
//    result[b] = result[b];
    }
    padding = strlen(result) + 1;
    system ("PAUSE");
  return result; <--
}

1 个答案:

答案 0 :(得分:1)

这可能不是代码中唯一的错误,但请注意您的原型如下所示:

char *addlarge(char, char, char);

,您的功能定义如下:

char *addLarge(char *number1, char *number2, char *result) {
   ...
}

尝试更改原型以匹配定义:

char *addlarge(char*, char*, char*);

希望这有帮助!