划分存储在 C 中的 char 数组中的任意大数

Dividing arbitrary large numbers stored in char arrays in C

我的家庭作业的一部分需要划分大整数,这些整数太长了,我只能将它们存储在字符数组中。除数和除数的长度都可以是一位到数千位,因此除法的结果也必须存储在 char 数组中,因为它也可能非常长。我想为每个索引存储一个数字。

我正在尝试使用重复减法,直到被除数小于除数并计算圈数。最坏的情况是除数为 2,所以我必须为计数器数组分配 'length of divident / 2' 内存量。

我已经实现了 subtractiongetLengthlengthCompare 函数,它们运行良好。这是我到目前为止所做的:

char *division(char *divident, char *divisor, int len_divident, int len_divisor)
{
    if (divident == NULL || divisor == NULL)
    {
        return NULL;
    }

    char *cnt = (char*)malloc((len_divident/ 2) * sizeof(char));
    char *res = subtraction(divident, divisor, len_divident, len_divisor);
    int i = 0;

    do
    {
        res = subtraction(res, divisor, getLength(res), len_divisor);

        if (cnt[i] == 9)
        {
            i++;
        }

        cnt[i]++;

    } while (lengthCompare(res, divisor) == 1 || lengthCompare(res, divisor) == 0);
    
    cnt->digits[i + 1] = '[=10=]';
    return cnt;
}

lengthCompare 函数 returns 如果第一个参数比第二个参数长则为 1,如果第二个参数更长则为 2,如果它们的长度相等则为 0。

此代码不起作用 - 每次我编译时都会收到“错误 - space 不够”消息。 编辑:具体来说,它是减法函数的一个例外: 抛出未处理的异常:写入访问冲突。 结果是 0x1110112.

请注意,我是 C 的初学者,这可能不是我想做的最好的方法,但我想不出更好的方法。

非常感谢大家的批评和建议!

编辑:na 重命名为除数和除数。

The worst case is ... , so I have to allocate 'length of divident / 2' amount of memory for the counter array.

不完全是,最坏的情况更接近减法。

代码没有分配足够的内存。

char *cnt = (char*)malloc((len_divident / 2) * sizeof(char));  // Bad

确保 除数 后,表示一个没有前导零的值 ...

while (len_divisor > 0 && divisor == '0') {
  len_divisor--;
  divisor++;
}

.....,需要的space不超过:

// As it looks like code is using strings
#define SPACE_FOR NULL_CHARACTER 1

size_t length = 1 + SPACE_FOR NULL_CHARACTER;
if (len_dividend > _len_divisor) {
  length = len_dividend - len_divisor + 1 + SPACE_FOR NULL_CHARACTER;
}

不需要在 C 中进行转换。如果想按指针类型缩放,最好使用 sizeof *pointer * 然后 * sizeof(type)。更容易正确编码、审查和维护。

char *cnt = malloc(sizeof *cnt * length);

健壮的代码会检查分配是否成功。

if (cnt == NULL) {
  Handle_OutOfMemory_Somehow();
}