Saturday, July 13, 2013

Using Pointers in C

Hello Alchemists!

I have a small example to show you written in C. C is a programming language created in the late 1960's by developers working at AT&T, made to abstract programmers from machine code in a way which would be simple to modify and program.

This example makes use of pointers, which are references to an address in memory which stores information. Pointers are used to save memory by referring to an object instead of copying it multiple times. It can also increase the speed of an operation by avoiding the copy operation.

You can read more about programming in C here:

http://www.cplusplus.com/doc/tutorial/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main() {

// Use array of characters s[] and assign 5 characters
char s[] = "What?";

// Define a pointer to s (s itself is already a pointer, so we don't have to use &)
char *p = s;

// Print first element of s[]
printf("%c\n", *p);

// Print the second element of s[]
printf("%c\n", *(p + 1));

// Print the third element of s[]
printf("%c\n", *(p + 2));

// Print the fourth element of s[]
printf("%c\n", *(p + 3));

// Print the fifth element of s[]
printf("%c\n", *(p + 4));

// Print the entire string
printf("The string is : %s\n", p);
}

No comments:

Post a Comment