How to Declare Pointer in C: Syntax and Examples
In C, you declare a pointer by specifying the type it points to followed by an asterisk
* and the pointer name, like int *ptr;. This means ptr holds the memory address of an integer variable.Syntax
To declare a pointer, write the type of data it will point to, then an asterisk *, and then the pointer's name. For example, int *ptr; declares a pointer to an integer.
- Type: The data type the pointer will point to (e.g.,
int,char). - Asterisk
*: Indicates that the variable is a pointer. - Pointer name: The variable name that stores the address.
c
int *ptr; char *charPtr; float *floatPtr;
Example
This example shows how to declare a pointer, assign it the address of a variable, and access the value through the pointer.
c
#include <stdio.h> int main() { int num = 10; int *ptr = # // Pointer holds address of num printf("Value of num: %d\n", num); printf("Address of num: %p\n", (void*)&num); printf("Pointer ptr points to address: %p\n", (void*)ptr); printf("Value pointed to by ptr: %d\n", *ptr); return 0; }
Output
Value of num: 10
Address of num: 0x7ffee3b8a8ac
Pointer ptr points to address: 0x7ffee3b8a8ac
Value pointed to by ptr: 10
Common Pitfalls
Common mistakes when declaring pointers include:
- Forgetting the asterisk
*, which makes the variable a normal variable, not a pointer. - Not initializing the pointer before use, which can cause it to point to a random memory location.
- Confusing the pointer declaration syntax, especially when declaring multiple pointers in one line.
Example of wrong and right pointer declarations:
c
int *ptr1, ptr2; // ptr1 is a pointer, ptr2 is an int variable // Correct way to declare two pointers: int *ptr3, *ptr4;
Quick Reference
| Declaration | Meaning |
|---|---|
| int *p; | Pointer to an int |
| char *c; | Pointer to a char |
| float *f; | Pointer to a float |
| int *p1, *p2; | Two pointers to int |
| int *p, x; | p is pointer to int, x is int variable |
Key Takeaways
Declare a pointer by writing the type, then an asterisk *, then the pointer name.
Pointers store memory addresses of variables of the declared type.
Always initialize pointers before using them to avoid undefined behavior.
Multiple pointers can be declared in one line by placing * before each name.
Remember that without *, the variable is not a pointer but a normal variable.