C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Lesson Three - About Chars

By David Bolton, About.com

2 of 3

Assigning Strings using Pointers.

Let me now introduce pointers. This is one of the most complex things to learn in C and the subject of a later lesson to itself.

A pointer holds the address of a variable. When your application is loaded into ram part of the ram holds the variables.

On the previous page we used the strcpy() function to assign a string. Another way to do this is with a pointer by using * after the type.

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

int main() {
char *name="David Bolton";
printf("My name is %s\r\n",name) ;

return 0;
}

The line char * name="David Bolton"; defines name as a pointer to the first character in the string. The assignment means that as soon as the program loads, the pointer is set to hold the address of where the string is stored. By adding these two lines after the printf, and making the example, you can see this.

printf("The address of name is %x\r\n",(int)&name) ;
printf("The address that *name points to is %x\r\n",(int)name) ;
%x prints the addresses in hexadecimal. The \r\n outputs a Carriage Return and a Linefeed character.

(int)&name has two important parts. (int) converts (it's called a cast) the pointer type to an int. &name means the address of the variable name. When this runs it prints the following. On your computer the two addresses may be different.

My name is David Bolton
The address of name is 7fe78
The address that name points to is 408004
On the next page : More about Pointers.

Explore C / C++ / C#

About.com Special Features

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Assigning Strings using Pointers.

©2009 About.com, a part of The New York Times Company.

All rights reserved.