I 'm writing a large number plus function, using arrays
#define MAXLEN 10
int * plus(int *a, int *b) {
int *result;
int tmp;
int add = 0;
result = (int *)malloc(MAXLEN); // A breakpoint exception was triggered
for (int i = MAXLEN - 1; i >= 0; i--) {
tmp = a[i] + b[i] + add;
add = 0;
if (tmp / 10) {
add = tmp / 10;
tmp = tmp % 10;
}
result[i] = tmp;
}
return result;
}
There's always exception on the malloc line, but in other functions the malloc() works well.
How does it happened?
Here are all the codes:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXLEN 10
int * plus(int *a, int *b) {
int *result;
int tmp;
int add = 0;
result = (int *)malloc(MAXLEN);
for (int i = MAXLEN - 1; i >= 0; i--) {
tmp = a[i] + b[i] + add;
add = 0;
if (tmp / 10) {
add = tmp / 10;
tmp = tmp % 10;
}
result[i] = tmp;
}
return result;
}
void deliver(int *a, int *b) {
for (int i = 0; i < MAXLEN; i++) {
a[i] = b[i];
}
}
void init_int(int *a) {
for (int i = 0; i < MAXLEN; i++) {
a[i] = 0;
}
}
int * numWays(int n) {
int *a, *b, *c, *sum;
int j;
a = (int *)malloc(MAXLEN);
b = (int *)malloc(MAXLEN);
c = (int *)malloc(MAXLEN);
init_int(a);
init_int(b);
init_int(c);
init_int(sum);
a[MAXLEN - 1] = 1;
b[MAXLEN - 1] = 1;
c[MAXLEN - 1] = 2;
for (int i = 0; i < n; i++) {
sum = plus(plus(a, b), c);
deliver(a, b);
deliver(b, c);
deliver(c, sum);
}
return a;
}
int main()
{
int print_flag = 0;
int *num;
num = (int *)malloc(MAXLEN);
num = numWays(4);
for (int i = 0; i < MAXLEN; i++) {
if (num[i]) {
print_flag = 1;
}
if (print_flag) {
printf("%d", num[i]);
}
}
printf("\n");
return 0;
}
It's a question about how many ways can a frog jump onto n steps if it can jump 1, 2 or three steps each time, and I want the exact number.