I’m learning C and I have written a simple program (just a tanning). On input you pass two arguments (row and column) and output you get a Calc (or Excel) code for this cell.
For example:
Input: 3 1 Output: A3
Input: 1 27 Output: AA1
The code:
#include <stdio.h>
char kol[7] = "";
unsigned int passes=0, nr;
int powa(unsigned int lv)
{
if(passes < nr)
{
if(kol[lv] == '\0')
{
kol[lv] = 'A';
kol[lv+1] = '\0';
} else
{
kol[lv]++;
if(kol[lv] == 'Z'+1)
{
kol[lv] = 'A';
powa(lv+1);
return 0;
}
}
passes++;
if(lv != 0)
{
powa(lv-1);
} else
{
powa(lv);
}
}
}
int main(void)
{
unsigned int wier;
int i, len=0;
scanf("%u %u", &wier, &nr);
powa(0);
while(kol[len] != '\0')
{
len++;
}
for(i=len-1;i>=0;i--)
{
putchar(kol[i]);
}
printf("%u", wier);
return 0;
}
But if I pass in a larger value (such as 300000000) I get a segmentation fault error. Why?
Are you experimenting with recursion? I don’t think I’d be using a recursive solution. You should probably not be using as many global variables as you are, either.
Assuming recursion is crucial, then in outline, I think I’d expect to use a solution such as:
Note that the revised
powa()returns a pointer to the null at the end of the data it has formatted. Theoretically, I should check the return fromsnprintf()to ensure no buffer overflow.SinceI have now compiled this, and tested and corrected it (the correction being to replace the recursive call...bogus...is not valid C, you can tell I’ve not compiled this, butpowa(div, buffer)withpowa(div - 1, buffer), a change necessary because the calculation needs to deal with 0 versus 1 as the starting point for counting. The recursion scheme seems simpler to me (a single recursive call instead of three of them in your code).Here is code to handle both scanning and formatting derived from the code above: