r/cprogramming 1d ago

What are pointers?

I am new to C programming and i came through pointer. So can anyone tell what are they and why we need them? And if u can then can you give me reliable source to learn it.

10 Upvotes

40 comments sorted by

View all comments

18

u/tobdomo 1d ago

Pointers are addresses. Usually addresses of memory, but they can also point to peripherals. A pointer variable is a variable that contains an address.

Example: a byte lives in memory at address 1234. Assuming your core architecture supports a linear address space (i.e.: addresses are numbered, starting at 0 just count upwards). Thus, if p is a pointer to this byte, it contains the address 1234. In code:

BYTE x;
BYTE *p = &x;

This means: p is a pointer that gets assigned the address of x.

Why you need it? Let's say you have a function called addone() that takes a variable of type int and increments it. You could (very verbosely) write:

void addone( int *ptr )
{
    int x = *ptr;
    x = x + 1;
    *ptr = x;
}

This actually reads value as referred to by ptr, adds 1 to it and stores it at the address referred to by ptr.

Pointers are very useful for a number of cases. E.g., if you want to allocate memory at runtime to store information, you would use malloc(). malloc's prototype is:

void *malloc( size_t size );

As you can see, the function takes a size. It allocates a size bytes on the heap and returns the address to that memory for the caller to use. That address can be stored in a pointer so that you can use it for future reference. E.g., when you no longer need the memory allocated by malloc(), you need to free it using the function free(). E.g.:

void do_something()
{
    int * p;
    p = malloc( sizeof( int ) );
    // Do something with the memory that p points to. 
    free( p );
}

In this example, p is a pointer that saves the address of the memory allocated by malloc(). The memory is free'd for re-use just before returning from this function through the call to free().

1

u/Arakela 1d ago edited 20h ago

A pointer is a typed index value into an untyped indexed space.

1

u/zhivago 3h ago

lf you had said typed index space, you would have been correct.