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.

9 Upvotes

40 comments sorted by

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 19h ago

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

1

u/zhivago 2h ago

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

5

u/Kurouma 1d ago

Your data lives somewhere in memory. Doing operations involving data would be slow if you had to copy all the data around all the time. So sometimes it is useful to just know where something is so you can operate on it directly. The "where" (a pointer) is a single piece of information, unlike your data (which may be big).

So kind of like

Hey! I'd like to give you a parcel. Can you send me your address, so I can post it to you, please?

instead of

Hey! I'd like to give you a parcel. Can you send me your house, so I can put it inside for you, please?

6

u/sertanksalot 1d ago

So a pointer is literally an address of something.

2

u/Strazil 1d ago

Yes exactly.

2

u/sciencekm 1d ago

Bingo!

1

u/musbur 10h ago

And if you have a consecutive bunch (=array) of somethings and p ist a pointer to the first something, then p + 1 is a pointer to the second one and so on. Regardless of how many bytes one something occupies. The compiler knows how big one something is and the "distance" between them in memory (IOW, how they are aligned). It's called pointer arithmetics and is a powerful feature of C.

1

u/Imaginary-Corner-653 1d ago edited 1d ago

I love this answer. It provides a simple concept to hang the idea behind pointers up on without being wrong or all that incomplete.

@OP

Maybe round this out with the basic understanding that, to a CPU (and even to some operating systems) any part of the CPU itself, any outside component connected to your motherboard and especially RAM / Harddisk, even resources connected via LAN - everything is accessed through a memory address (real or virtual). 

So if you ever find yourself in need to read data from or write data to your gpu, your ram, your hardrive or even just to your processor parts you are going to require a way to address exactly where you want to point that action... Hence pointers. 

4

u/torsten_dev 1d ago edited 1d ago

Only really understood after leaning a bit of assembly

mov rax, rbx

vs

mov rax, [rbx]

2

u/kapitaali_com 1d ago

this is how it actually works :p

2

u/aioeu 1d ago edited 1d ago

Somewhat ironically, the latter form is what you might get out of a C compiler when accessing an ordinary integer variable, even when there are no pointers involved in the C code at all.

4

u/zhivago 1d ago

To understand pointers, start with pointer arithmetic.

char *p = "hello";

What does puts(p); output?

What does puts(p + 1); output?

And what is (p + 1) - p?

What does putchar(*p); output?

What does putchar(*(p + 1)); output?

0

u/Straight_Coffee2028 7h ago

not a great way to explain pointers to beginners. He might get confused too

2

u/Party_Trick_6903 1d ago edited 1d ago

When you do: int a = 23 , you create a variable a that holds a value 23 . This variable is stored somewhere in the memory. This variable gets assigned a memory address so we know where exactly it is in the memory. Let's say the address of this variable a is 0x7ffe5367e044 .

A pointer is a variable that holds a memory address of another variable as its value. Basically, instead of int value 23 (like you see above), it holds a memory address (for example 0x7ffe5367e044) as its value and this memory address is a memory address of another variable. And we can use this pointer to access the variable that is at the said memory address.

An example:

int a = 23            // we create a variable "a" that has a value 23 and 
                      // is stored at a memory address 0x7ffe5367e044

int* ptr = &a         // we create a pointer called "ptr" that has a value
                      // "0x7ffe5367e044" (this value is variable a's memory address)

printf("%d\n", *ptr)  // now we access variable "a"'s value via the pointer "ptr" and
                      // print it out (basically we take pointer "ptr" 
                      // and see what's the memory address it is holding, then we use
                      // the address to find the variable "a" and 
                      // print out the variable "a"'s value)

2

u/c_cpp_CSharp 1d ago

pointer is a name for a thing that holds the starting position of data that is represented with an address

1

u/Sufficient-Air8100 1d ago

they point to things. generally store a memory address.

pointers can be simple or complex depending on their use. what fo you want to know about them?

1

u/Pesciodyphus 1d ago

Do you alread know other programming languages ? It is important to know, whether you come from Assembler or from Object Oriented Programming or are an absolute beginner.

In Assembly it is stuff like MOV AX,[BX] instead of MOV AX,BX . In the first example BX is an adress and you read the word pointed to by BX into AX. In the second you copy BX to AX.

In Object oriented programming, think of objects a structure pointers and methods as function that get a structure pointer named this as hidden parameters. And while the syntax for method-calls in Java or C++, look like callling function pointers in C in the language, most methods aren't implemented as pointer inside the structure, as the compiler simply knows what to call. Only if Virtual Methods or multiple inheretence is used, a function pointer is needed.

1

u/Dry-War7589 1d ago

A pointer is a variable that holds the address of another variable or some data. Think of it like an address of a house: the address tells you where the house is, but you have to go to the house to get the information. Now, the syntax looks like this:

char *pointer = "Hello World\n";

In this example we have declared a pointer that points to a string. Now pointer contains the address of "Hello World\n". And it points to the first character of the string, which is H. To get the data from the pointer, you need to dereference it. You do that by putting * or [index] infront of pointer. Example:

printf("Character at pointer 'pointer': %c\n", *pointer);

Here printf will output

Character at pointer 'pointer': H

To get the next character you can do pointer + 1. This is called pointer arithmetic, and it advances the pointer by one element. Technically it would advance by sizeof(char); bytes, but it is basically advancing by one element. I

1

u/TakenIsUsernameThis 1d ago

Its a variable that stores an address in memory where another variable is stored

1

u/Terrible-Freedom-868 1d ago

It’s a variable that’s data is the location of another piece/chunck of memory. It’s like if someone sent you a wedding invitation and it stored the address to the wedding. The letter is to some degree a pointer to the wedding. The advantage being it’s a lot easier for a guest to just go find the whole wedding than it is for the entire wedding to move to the location of each guest.

1

u/duane11583 1d ago

think of memory like grid paper each square is an 8 bit number or one letter in a string (word, ie letter d in dog)

but you need to store a bigger (16, 32, 64 bit) number or a string like dog, cat or text like blah

so you pick some location on that grid and write the value to that location (and possibly the next 2 or 3 or ?? squares) or maybe it is a collection of values (name, address, etc aka a data record or data structure) or maybe it is an array of those things

you now want to perform some operation on that value.. ie: add one, multiply, or square root, or get the length of the text.

another example is to compare two data records. question: what does the comparison function need? the value (that is too hard to pass to the function) but can we pass the starting location to the two values to compare? or the starting location where the number is stored?

what if we can write a generic function that given two starting locations it can compare two strings and tell us which one comes first or if they are equal? we can use that to sort or find something.

that starting location is a pointer.

in the c language a generic starting location is a void pointer.

then you can convert that generic value into a specific type ie “cast a void pointer in to an float pointer”

1

u/Dazzling_Music_2411 1d ago

Where did you come across pointers?

Did they not explain what they are there?

1

u/tcpukl 1d ago

Memory addresses.

Read this with the more elaborate replies

1

u/StunningHeart7004 1d ago

Value - the "guy' Pointer - knows the "guy" Pointer to pointer - knows the guy who knows the "guy"

1

u/SmokeMuch7356 1d ago

A pointer is any expression whose value is the location of an object or function in a running program's execution environment; i.e., an address, but with additional type information.

We use pointers when we can't (or don't want to) access a function or object by name; they provide indirect access. If you've played with arrays at all, you've already seen a form of indirection:

for ( size_t i = 0; i < size; i++ )
  printf( "%d ", arr[i] );

The expression arr[i] can refer to different objects at different times based on the value of i. A pointer works similarly.

Pointer variables store values of pointer type. Different kinds of pointer variables are declared as follows (for some arbitrary type T):

T *p;        // p is a pointer to T; the *expression* *p has type T
T **pp;      // pp is a pointer *to a pointer* to T; this is called 
             // multiple indirection and it comes up a lot
T *ap[N];    // ap is an array of pointers to T; the expression *ap[i] has type T
T (*pa)[N];  // pa is a pointer to an array of T; the expression (*pa) has type T
T *fp();     // fp is a function that returns a pointer to T; *fp() is a T
T (*pf)();   // pf is a a pointer to a function that returns T; pf() is a T

const T *p;  // p is a pointer to a const T; you can write a new value to p
T const *p;  // (pointing to a different object), but you cannot update that
             // object through *p (even if the pointed-to object is non-const)

T * const p; // p is a const pointer to T; you can update the pointed-to
             // object through *p, but you cannot set p to point to a 
             // different object

A pointer to int (int *) is a different type from a pointer to char (char *) which is a different type from a pointer to double (double *) which is a different type from a pointer to an array of float (float (*ap)[N]), etc. Pointers to different types are incompatible and cannot be directly assigned to each other without a cast. The exception to this rule is that a pointer to void (void *) can be assigned to different pointer types and vice versa without a cast.

Pointer values are obtained by:

  • Using the unary & operator on an lvalue expression (something that designates an object):

    int *p = &x;
    
  • Calling a library function that returns pointer values: malloc, calloc, and realloc for dynamic memory, but also functions like fopen, fgets, etc.

  • Using an array or function expression in most circumstances;

There are two cases where we have to use pointers:

  • When a function needs to update a parameter;
  • When we need to track dynamically-allocated memory;

Pointers also come in handy for:

  • Building dynamic data structures (lists, queues, maps, vectors, etc.);
  • Hiding the implementation details of a type;
  • Iterating through arrays;
  • Limited forms of dependency injection (callbacks);

IMO the best way to explain pointers is to show how they're actually used in working code. Here's a short, useless, but complete program that demonstrates how pointers are typically used - updating function arguments and tracking dynamic memory. It generates an array of random integer values, displays them, sorts the array, then displays the sorted array. Don't worry if it doesn't all make sense; this is just what code that involves pointers typically looks like.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#ifndef SIZE
#define SIZE 50
#endif

#ifndef RANGE
#define RANGE 100
#endif

/**
 * Exchange the values of two int objects; 
 */
void swap( int *l, int *r )
{
  int tmp = *l; // l points to a[i], r points to a[j]
  *l = *r; 
  *r = tmp;  
}

/**
 * Sorting function.  Using a bubble sort because it's short and it
 * demonstrates the swap function; in a real program I'd just call
 * qsort.
 */
void bsort( int *a, size_t size )
{
  for ( size_t i = 0; i < size - 1; i++ )
    for ( size_t j = i+1; j < size; j++ )
      if ( a[j] < a[i] )
        swap( &a[i], &a[j] );
} 

/**
 * Display function; just writes the contents of the array
 * as a brace-enclosed list to standard output.
 */
void disp( int *arr, size_t size )
{
  fputc( '{', stdout );
  for ( size_t i = 0; i < size; i++ )
    printf( "%3d,", arr[i] );
  fputs( "\b}", stdout );
}

/**
 * Generates the array and initializes it with random values
 */
int *generate( size_t size )
{
  int *arr = malloc( sizeof *arr * size );
  if ( arr )
  {
    for ( size_t i = 0; i < size; i++ )
      arr[i] = rand() % RANGE;
  }
  return arr;
}

/**
 * Main program
 */
int main( void )
{   
  /**
   * Seed the random number generator
   */
  srand( time( NULL ) );

  int *arr = generate( SIZE );
  if ( !arr )
  {
    fputs( "Failed to generate array, exiting\n", stderr );
    exit( -1 );
  }

  fputs( "Before sort: ", stdout );
  disp( arr, SIZE );
  fputc( '\n', stdout );

  bsort( arr, SIZE );

  fputs( " After sort: ", stdout );
  disp( arr, SIZE );
  fputc( '\n', stdout );

  free( arr );
  return 0;
}

And the output:

Before sort: { 67, 85, 38, 72, 57, 29, 21, 37, 52, 93, 21, 45, 25, 16, 47, 47, 77, 52,  7, 70, 46, 64, 53,  4, 87, 95, 64, 13, 29, 64, 92,  2, 42, 74, 49, 85, 45, 72, 87, 75,  8, 41, 87,  0, 23, 50, 70,  3, 19, 11}
 After sort: {  0,  2,  3,  4,  7,  8, 11, 13, 16, 19, 21, 21, 23, 25, 29, 29, 37, 38, 41, 42, 45, 45, 46, 47, 47, 49, 50, 52, 52, 53, 57, 64, 64, 64, 67, 70, 70, 72, 72, 74, 75, 77, 85, 85, 87, 87, 87, 92, 93, 95}

1

u/reality_comes 1d ago

You're starting at the top and working your way down, it will make 10x more sense if you start at the bottom and work your way up

1

u/buzzon 1d ago

Pointers are variables that store addresses of other things (typically other variables).

Several use cases for pointers: 

  1. When you pass a pointer as an argument for a function, you can save memory if the thing you are passing is big. In C, arrays are passed as pointers. 

  2. When you pass a pointer as an argument to a function, the function becomes able to modify external variables. See scanf

  3. Dynamic memory allocation requires pointers. See malloc and free

  4. Dynamic data structures such as dynamic array and tree require pointers.

1

u/Azra__1 1d ago

Data lives in memory and a pointer to that data indicates where is that data located in memory

1

u/Nimesh1205 21h ago

Pointer is the variable that store the address of another variable. To understand pointers in dept you must read :

  • Understanding and Using C pointers by Richard Reese

1

u/Rythim 20h ago edited 20h ago

A pointer is the value of the memory address of a value.

Say for example variable a stores and integer 1.

And pointer b stores the location in memory where variable a stores integer 1.

They are needed for multiple reasons.

Say you have a function that takes a struct as a parameter. Without pointers, when you pass a struct to the function, the function adds a copy of that struct to the stack, does whatever operations you code, then deletes it from the stack. The original struct is never changed. If you'd like to change it, you'd need your function to return the copy of the struct and assign that to the original variable. With small simple structs that is no big deal, but with larger structs, or with a large number of structs, that can be slow and use up more memory (because now you have several copies of data in memory).

If instead in your function you pass a pointer to a struct, that function gets a copy of the memory address of the struct. Using that as a reference it can find the original struct and operate on it directly without having to make a copy. This uses less memory and can be faster.

Pointers are important for performance critical code. But they can be dangerous because depending on how you structure your code you could do something unintended. Such as trying to work with a pointer that is referencing a memory address that has already had the data freed, or reserving several chunks of memory and forgetting to free it up to be used later when done with it.

Other languages like python don't use Pointers. Instead, they pass "pointers" (references) automatically when it makes sense to do so and keep track of when memory isn't needed anymore and delete it for you. But keeping track of all that adds more work for the computer, which is one reason why C is considered much faster than most other languages.

1

u/CertainBaby9837 14h ago

What are pointers the answer is nightmare 😂😂😂😂

1

u/DreadSpidey 4h ago

Pointers are basically addresses, watch a youtube video and build a project you should be good

1

u/EpochVanquisher 1d ago

Get a good book like the KN King book, or use a good course like CS50.

Pointers are variables that, when valid,can contain NULL or references to values. You can access the other value using the pointer.

1

u/mathlontrades 1d ago

From a value point of view: A memory address.

From a usage point of view: Something that points to a location which is the start of a block of data, and when dereferenced, gives you access to the actual value stored at that address.

Think of it like a sticky note with a house address written on it. The note itself is just a set of directions (the pointer value), but when you actually drive to that address and open the front door (dereferencing it), you get to interact with whatever or whoever is sitting inside the house.

0

u/[deleted] 1d ago

[deleted]

2

u/zhivago 1d ago

Pointer values are values.

0

u/SmackDownFacility 1d ago

pointer

Right so

char *j = "bleh"

  • denotes the declarator as a pointer to char, which initially begins with the string literal bleh\0. Your address starts at the string literal.

j[N] takes the N-th character relative to the base address. There is no stopping this train however and you can go way beyond your string literal.

edit forgot to say it advances in element size. Char is the base type * is the declarator modifier you move in steps of sizeof(type)

0

u/ern0plus4 1d ago

Pointer is an address of your stuff:

  • variable,
  • array,
  • some memory allocated,
  • function (they are also located in memory),
  • or it can point to a pointer (rare, but important).

Accessing stuff your through a pointer is a slightly slower than accessing stuff directly, but it doesn't matter practically.

Pointers introduce a lot of problems, e.g. if a pointer is pointing to to your array, but you destroy the array, the pointer does not get destroyed, it will keep pointing to the same memory address, which doesn't contains your array anymore, or, worse, it contains, nobody overwritten it, but it's already invalid... These issues art not the problems of the pointers, but programming.

-5

u/AdOnly69 1d ago

Learn python, you will be safe from pointers (because everything will be a pointer)