« »

Introduction to C

So I thought C was going to be impossible to understand, but so far (which is admittedly not that far), it’s not too different from the other programming languages I’ve encountered—though malloc (it even sounds ominous) and all the $ and * loom threateningly over the horizon.

I’m struggling with the finer points of pointers (more a syntactical problem I think than a conceptual one), as is evident from my first piece of C code, which takes a string (right now one that’s hard-coded into the program) and reverses it. I realized while I was coding that what takes so long about learning new languages is figuring out how to do the little easy stuff you take for granted. For instance, I wanted to find the length of the array in which I was storing my string but had no idea what the syntax was in C (I have since learned you can use sizeof()), so I ended up writing my own function instead.

This is the code:

by alex kauffmann

This is a totally inelegant solution but it
works, though I couldn't fully wrap my head around
the pointers (which is why I have both an array and
a more C-ish asterisk thingie).  

#include <stdio.h>

void main() {

  int i,a,b;
  char *s;

  s="satan oscillate my metallic sonatas";

  printf("The original string is: %s\n", s);
  printf("The reversed string is: ");

  for (i = 0; *s != '\0'; s++)  // counts the characters
     i++;                       // in the string

  char rs[i];                   // holds the reversed string

  for (a=i; a>0; s--) {
     rs[i-a]=*(s-1);            // (s-1) offsets the first
     a--;                       // character to skip the '\0'

  for (b=0; b



Comments are closed.