01/22

An Introduction to C

Part X, 20130122

It's time for a cake walk. Here's an array of integers.

int values[10];
int i;
for (i = 0;i < 10;i++) {
  values[i] = 2 * (i + 2);
  printf("The value at i %d is %d\n", i, values[i]);
}

That's it. Floats and other data types work pretty much the same way. Arrays of arrays are a little different, but this is good enough to get started with. Play with that a bit and move on to pointers.

So, you've come this far which tells me you really want to learn some C. The main thing that turns people off to C is pointers. I am about to show you that pointers aren't all that hard (to use anyway).

So, what's a pointer? A pointer is a special variable type that is used to hold the address of a location in memory. Here is a really hasty and terrible example:

int index, *pointer1, *pointer2;
index = 42;
pointer1 = &index;
pointer2 = pointer1;
printf("%d %d %d\n", index, *pointer1, *pointer2);
*pointer2 = 24;
printf("%d %d %d\n", index, *pointer1, *pointer2);

So, this is a useless program in general, but what I want to draw your attention to is the difference between the result of the first print statement and the second. Before I do so, I need to explain the two new symbols here. We have &index which means "the address of the variable named index". We also have *pointer1 and *pointer2 which mean "the value of the data stored at this address". Now, the output of the first print statement will be "42 42 42" and the output of the second will be "24 24 24" despite using different names for all of these assignments (the content of the memory location changed, see?).