What int * means in C
In C, int * is a pointer type. It reads as “pointer to int.” A pointer doesn’t hold a number. It holds the memory address of an int. The type int is one of the primitive data types in c, and int * is the pointer version of it.
#include <stdio.h>
int main(void) {
int count = 5;
int *where = &count; /* where holds the address of count */
printf("%d\n", count); /* prints 5 */
printf("%d\n", *where); /* prints 5, read through the pointer */
*where = 10; /* writes through the pointer */
printf("%d\n", count); /* prints 10 */
return 0;
}
Two operators do the work here:
&counttakes the address ofcount.*wherefollows the pointer to the value stored at that address. This is called dereferencing.
Reading the declaration
The star goes with the variable name, not with the type. In int *a, b;, only a is a pointer. b is a plain int. Writing int* a, b; looks as if both are pointers, but the rule doesn’t change: b is still an int. When you use pointers, declare one variable per line so each one is clear.
Passing a pointer to a function
A pointer lets a function change a variable that belongs to its caller. Parsing code sometimes uses this pattern, since it gives the caller a place to store the result:
#include <stdio.h>
#include <stdlib.h>
void read_number(const char *text, int *result) {
*result = atoi(text);
}
int main(void) {
int number = 0;
read_number("123", &number);
printf("%d\n", number); /* prints 123 */
return 0;
}
This example uses atoi, which can’t report errors, so real code needs more checks. For how atoi behaves with bad input, see What does the atoi() function do in C?
Pointers that point nowhere
A pointer that hasn’t been set points to an unknown address. Using it can crash the program. Set a pointer to NULL when it has no target yet, and check it before you use it:
int *target = NULL;
if (target != NULL) {
*target = 1;
}
Where int * shows up
You’ll meet int * in a few common places:
- Function parameters that need to change a variable in the caller.
- Arrays passed to a function. An array often arrives in the function as an
int *that points to its first element. - Output parameters, where a function stores its result through a pointer.
Summary
An int * is a pointer to an int. Use & to get an address and * to read or write the value at that address. Set pointers to NULL until they point at something. For turning text into numbers, see c convert string to int.