Search code examples
cfunctionpoint

Using a pointer to print a string from another function


So I'm writing a chess program from the ground up to work on my coding, and I've run into a problem I can't figure out. Here's the important bits for my question:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int printboard(char board[8][8])
{
    int i, x, y;
    char piece;
    char *clrptr, *nmptr;

    printf("\n");

    for (x=0; x<=40; x++)
    {
        if (x%5 == 0)
        {
            for (i=0; i<8; i++)
            {
                printf("|---------|");
            }
            printf("\n");
        }
        if (x%5 == 1 || x%5 == 4)
        {
            for (i=0; i<8; i++)
            {
                printf("|         |");
            }
            printf("\n");
        }
        if (x%5 == 2)
        {
            for (i=0; i<8; i++)
            {
                piece = board[x/5][i];
                int colorstr(char piece, char* clrptr);
                printf("|   %c%c%c   |", *clrptr, *clrptr+1, *clrptr+2);
            }
            printf("\n");
        }
    }
    return 0;
}

int colorstr(char piece, char* clrptr)
{
    char black[4] = "Blk", white[4] = "Wht", empty[4] = "000";

    if (isupper(piece) != 0)
        clrptr = black;
    if (piece == '0')
        clrptr = empty;
    else
        clrptr = white;
    return 0;
}

The idea is that piece is defined as an alphanumeric character from my board array, while the colorstr function determines what piece character makes what color, and then assigns clrptr to point to the first character in the relevant string array (black, white, or empty). Back in the main function, clrptr, clrptr+1, and clrptr+2 are printed, which in effect prints the string that colorstr determines. Or at least, that's my intent. I'm getting ▒▒▒ instead. The nmstr function does the same thing, so solving this problem should fix both.

(My compiler is cygwin-gcc.)


Solution

  • Your colorstr is a noop. Also, for a proper working function you should adjust parameters and return type. Try:

    char* colorstr(char piece)
    {
        return piece == '0' ? "000" : (isupper(piece) ? "Wht" : "Blk");
    }
    

    When you call it:

    for (i=0; i<8; i++)
    {
        piece = board[(unsigned char)x/5][i];
        clrptr = colorstr(piece); /* clrptr is returned
          (was a local declaration before) */
        printf("|   %s   |", clrptr);
    }
    printf("\n");