Menu
Coddy logo textTech

Declaring Pointers

Part of the Logic & Flow section of Coddy's C journey — lesson 2 of 63.

Now that you understand what pointers are, let's learn how to create them. Declaring a pointer variable follows a specific syntax that tells the compiler what type of data the pointer will point to.

The basic syntax for declaring a pointer is: data_type *pointer_name;

int *ptr;        // Declares a pointer to an integer
char *ch_ptr;    // Declares a pointer to a character
float *f_ptr;    // Declares a pointer to a float

The asterisk (*) is what makes this a pointer declaration. It tells the compiler that this variable will store a memory address, not the actual data value. When you declare int *ptr;, you're saying "ptr is a pointer that can store the address of an integer variable."

It is good practice to initialize pointers to NULL if they are not yet pointing to a valid memory address. This prevents them from pointing to random memory locations: int *ptr = NULL;

When printing pointer addresses using printf, use the %p format specifier. It is often recommended to cast the pointer to (void *) to ensure compatibility and correct formatting: printf("%p", (void *)ptr);

Notice that the data type before the asterisk specifies what kind of data the pointer will point to. This is important because different data types take up different amounts of memory space, and the compiler needs to know this information for proper memory management.

challenge icon

Challenge

Easy
Write a C program that demonstrates proper pointer declaration syntax. Your program should:
  1. Declare a pointer to an integer named int_ptr, initialized to NULL
  2. Declare a pointer to a character named char_ptr, initialized to NULL
  3. Declare a pointer to a float named float_ptr, initialized to NULL
  4. Print the memory addresses stored in each pointer using printf with the %p format specifier. When printing, cast the pointer to (void*) to ensure correct formatting, for example: printf("Label: %p\n", (void*)ptr);

Your output should display the three pointer addresses in the following format:

Integer pointer: [address]
Character pointer: [address]  
Float pointer: [address]

Note that the actual memory addresses will vary, but the format and labels must match exactly as shown above.

Try it yourself

#include <stdio.h>

int main() {
    // TODO: Declare your pointers here
    
    
    // TODO: Print the pointer addresses using the required format
    
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow