I have to use malloc() and free() to work with microsoft compiler. Each recursion adds a leading zero to store, even though it's not needed most of the time. After the for loop with % and /, qtnt will always be zero since store is longer than it needs to be.
Code:
#include <stdio.h>
#include <stdlib.h>
void raisePowerOf2(int array[], int pow);
int main()
{
int a[2] = {1,-1};
raisePowerOf2(a, 32);
return 0;
}
void raisePowerOf2(int array[], int pow){
int i, len, *store, qtnt=0;
for(i=0; array[i] != -1 ; i++);
len = i;
store = malloc((len+2)*sizeof(*store));
for(i = len-1; i >= 0; i--){
store[i+1]=(array[i]*2)%10+qtnt;
qtnt=(array[i]*2)/10;
}
store[0] = qtnt;
store[len+1] = -1;
if(pow > 1)
raisePowerOf2(store, pow-1);
else{
for(i=0; i <= len; i++)
printf("%d",store[i]);
}
free(store);
}
This version uses malloc() and realloc() to resize an allocated array only as needed:
Code:
#include <stdio.h>
#include <stdlib.h>
void raisePowerOf2(int **pa, int pow);
int main()
{
int * a = malloc(2 * sizeof(*a));
a[0] = 1;
a[1] = -1;
raisePowerOf2(&a, 32);
free(a);
return 0;
}
void raisePowerOf2(int **pa, int pow){
int *a = *pa;
int i, len, a2, qtnt = 0;
for(i = 0; a[i] != -1; i++);
len = i;
for(i = len-1; i >= 0; i--){
a2 = a[i]*2;
a[i]=a2 % 10 + qtnt;
qtnt=a2 / 10;
}
if(qtnt){
len += 1;
*pa = a = realloc(a, (len+1) * sizeof(*a));
for(i = len; i > 0; i--)
a[i] = a[i-1];
a[0] = qtnt;
}
if(pow > 1)
raisePowerOf2(pa, pow-1);
else{
for(i = 0; i < len; i++)
printf("%d", a[i]);
}
}