Pointers, the way I learned them in school!

In the following code,

char my_character = 'a';

we are creating a new variable called my_character and storing ‘a’ there.” This will be one byte in size.

But in the following code, we’re trying to stuff a bunch of characters into a single character.

char my_text = "Hello World!";

You cannot do that. So what data type makes it possible to create a string of text? The answer is none. There is no ‘string of text’ data type. No variable will ever hold a string of text. Even a pointer cannot hold a string of text. A pointer can only hold a memory address.

The key point here is a pointer cannot hold the string itself, but it can hold the memory address of the first character of a string.

Consider this:

char *my_pointer;

We have created a pointer called my_pointer which can contain a memory address.

Now consider this code:

char *my_pointer;
my_pointer = "Hello World!";
printf("The string is: %s \n", my_pointer);

Whenever you create a string of text in the C language with quotes, you are actually storing that string somewhere in memory. That means that a string of text, just like all variables, has some address in memory where it lives. Now a pointer can only contain a memory address, so “Hello World!” must be a memory address. You are effectively telling the compiler to create the string of text “Hello World!” and store in memory at some memory address and to create a pointer called my_pointer and point it to the memory address where the string “Hello World!” is stored.

First, a functioning sample before we start breaking stuff:

#include 
int main() {
    char *string = "This string gets lost";
    string = "Hello World!";
    printf("String is: %s\n", string);
}

and the output would be “String is: Hello World!”

So what is the difference between these two below?

char string[] = "Hello World!";
char *string = "Hello World!";

If you try to modify the string[] after assigning it, you’ll get an error: invalid array assignment, or incompatible types in assignment of const char, so you’ll have to comment it out, just like in the code below:

#include 
int main() {
  char string1[] = "Hello1";
  char *string2 = "Hello2";

//  string1 = "hELLO1";
  string2 = "hELLO2";

  printf("String #1: %s\n", string1);
  printf("String #2: %s\n", string2);
}
Posted by admica   @   5 October 2009

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

*

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse

Valid XHTML 1.0 Transitional