Saturday, February 1, 2025

Fun C Code Challenge

I haven't done any programming in a good long while. I started dabbling with some C over the past week, and happened across Dan Gookin's C For Dummies blog, where he posted a neat little multi-dimensional array manipulation challenge. I found the subscript notation to be trivial compared to getting the initial pointer notation correct. You can see Dan's post here.

    // Code challenge:
    // Output the string, "I am an excellent C programmer"
    // From Dan Gookin's "C For Dummies" blog
    // https://c-for-dummies.com/blog/?p=6791

#include <stdio.h>

int main(void)
{
    char *a[] = { "I", "good", "language" };
    char *b[] = { "am", "C", "excellent", "an" };
    char *c[] = { "a", "programmer", "very" };
    char **z[] = { a, b, c };

    // Easier way:
    printf("%s %s %s %s %s %s.\n",
           z[0][0],
           z[1][0],
           z[1][3],
           z[1][2],
           z[1][1],
           z[2][1]
    );

    // A bit trickier for this rusty old mind. :)
    printf("%s %s %s %s %s %s.\n",
           *(*(z + 0) + 0),
           *(*(z + 1) + 0),
           *(*(z + 1) + 3),
           *(*(z + 1) + 2),
           *(*(z + 1) + 1),
           *(*(z + 2) + 1)
    );

    return 0;
}

No comments:

Post a Comment