问题:
示例:
我将数字存储在这样的结构中:
typedef struct Arbitrary_Large_Integer
{
char digits[];
} ALI;
要求:
代码:
ALI *subtraction(ALI n, ALI a, int nLength, int aLength)
{
ALI *result;
result = (ALI*)malloc(nLength * sizeof(ALI));
if (result == NULL)
printf("ERROR");
int temp_n, temp_a, difference;
int i = nLength - 1; //iterator for number 'n'
int j = aLength - 1; //iterator for number 'a'
int k = 0; //iterator for number 'k', n - a = k
bool carry = false; //to decide whether a carry is needed or not the turn
for (i; i >= 0; i--)
{
//subtracting 48 from n.digits[i], so temp_n gets the actual number
//and not its ASCII code when the value is passed
temp_n = n.digits[i] - ASCIICONVERT;
temp_a = a.digits[j] - ASCIICONVERT;
//Performing subtraction the same way as it's used on paper
if (carry) //if there is carry, a needs to be increased by one
{
temp_a++;
carry = false;
}
if (temp_n >= temp_a)
{
difference = temp_n - temp_a;
}
//I wrote else if instead of else so I can clearly see the condition
else if (temp_a > temp_n)
{
temp_n += 10;
difference = temp_n - temp_a;
carry = true;
}
//placing the difference in array k, but first converting it back to ASCII
result->digits[k] = difference + ASCIICONVERT;
k++;
//n is certainly longer than a, so after every subtraction is performed on a's digits,
//I place the remaining digits of n in k
if (j == 0)
{
for (int l = i - 1; l >= 0; l--)
{
result->digits[k] = n.digits[l];
k++;
}
//don't forget to close the array
result->digits[k] = '\0';
break;
}
j--;
}
//reverse the result array
_strrev(result->digits);
return result;
}
输出/错误:
答案 0 :(得分:1)
问题:
非标准C
typedef
不是有效的标准C结构。除弹性阵列成员外,弹性阵列成员(FAM).digits
还必须至少有一个其他的具名命名成员。建议将.nLength
作为第一位成员。
// Not standard
typedef struct Arbitrary_Large_Integer {
char digits[];
} ALI;
malloc(0)
?
由于代码使用的是非标准C,因此请注意nLength * sizeof(ALI)
可能与nLength * 0
相同。
没有空字符可以容纳
代码正在尝试将.digits
与_strrev()
一起用作 string ,mallloc()
至少要小1。
可能存在其他问题
Minimal, Complete, and Verifiable example可用于其他修复程序/解决方案