I am not a C programmer. I have just started reading K&R’s TCPL last week.
I have written this 42 line code in Java. I tried converting it to C, but it is giving me a segmentation fault.
Here is the Java version: http://codepaste.net/m8jz6m
My failed attempt to port it to C:
//Not working.
#include <stdlib.h>
#include <string.h>
void caesar ( const int SIDE )
{
int array [SIDE] [SIDE] ;
for ( int number = 1; number <= SIDE * SIDE; ++ number )
array [ getY ( number, SIDE ) ] [ getX ( number, SIDE ) ] = number ;
for ( int Y = 0; Y < SIDE; ++ Y ) {
for ( int X = 0; X < SIDE; ++ X)
printf ( sprintf ("%%%dd" , strlen(itoa(SIDE*SIDE))), array [Y] [X] );
printf ("\n");
}
}
int getX ( const int number, const int SIDE )
{
return SIDE == 1 ? 0 : number > 4 * SIDE - 4 ? 1 + getX ( number - 4 * SIDE + 4, SIDE - 2 ) : number >= 3 * SIDE - 2 ? 0 : number >= 2 * SIDE - 1 ? 3 * SIDE - 2 - number : number > SIDE ? SIDE - 1 : number - 1 ;
}
int getY ( const int number, const int SIDE )
{
return SIDE == 1 ? 0 : number > 4 * SIDE - 4 ? 1 + getY ( number - 4 * SIDE + 4, SIDE - 2 ) : number >= 3 * SIDE - 2 ? 4 * SIDE - 3 - number : number >= 2 * SIDE - 1 ? SIDE - 1 : number > SIDE ? number - SIDE : 0 ;
}
void main ( int argc, char *argv )
{
if ( argc == 0 )
printf ("\tUsage: java Caesar [side] | side:> Length and breadth of the square.\n");
else
caesar ( atoi( argv[1] ) );
}
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
Please let me know where I am going wrong.
You are calling your
itoa()function with one argument, while the function actually expects two.Also, it seems that this line:
could be better expressed with something like:
without using those
getXandgetYfunctions (that are curiously recursive). I haven’t examined those functions in detail to see what they actually do, but you may consider the above modification in any case.sprintf()is called with incorrect arguments. The first parameter should be the destination buffer. You seem to be using it as if it returned a string (it doesn’t).Look up the function of
*inside a printf format specifier.