1

I am struggling to understand the usefulness of pointers. I've read answers to similar questions but they don't seem to make things clear for me.

Lets say we want to allocate some space dynamically for the use of a variable, we would do something like this: int *i = malloc(sizeof(int)). I do not understand why the creator(s) of C felt the need to have a pointer that does the job. Why wouldn't they have malloc return (void) type of memory (correct me if that's not possible in general) instead of a (void*) pointer to that memory. The syntax for that would be something like int i = malloc(sizeof(int)).

I understand that the question may be abstract because I don't have all the knowledge that is needed to explain what I have in my brain. If something that I say doesn't make sense feel free to tell me so that I can elaborate. Thank you in advance!

BillTheKid
  • 377
  • 1
  • 13
  • You don't need to use `malloc` for the single variable in your example, defining `int i;` does the job, and then the syntax `int i = 42;` would assign an initialised *value* to `i`. – Weather Vane Nov 24 '21 at 09:20
  • @WeatherVane I understand that I have this option in the specific case, but that doesn't answer why pointers are needed in C when allocating memory dynamically. – BillTheKid Nov 24 '21 at 09:24
  • For a variable length array (where supported), they aren't necessary. You can define `int len = 42; int i[len];` to dynamically define an array (and you don't have to clean up) but its scope will be limited. – Weather Vane Nov 24 '21 at 09:25
  • @WeatherVane Could you tell me where I can read what are the cases that are necessary, please? – BillTheKid Nov 24 '21 at 09:27
  • Related: [Why Use Pointers in C?](https://stackoverflow.com/questions/29423757/why-use-pointers-in-c) – Weather Vane Nov 24 '21 at 09:32
  • There's no rationale behind why most things in C were designed as they were, they just happened. I'm guessing malloc was a thin wrapper around some already existing Unix function like sbrk. Unless someone can dig up any references from Dennis Ritchie's old paper regarding the creation of C, I don't think the question can be answered. Notably, much more modern languages like Java do heap allocation exactly like you describe it. – Lundin Nov 24 '21 at 09:34
  • I just checked the above mentioned paper and this is the only reference to dynamic allocation I could find: [_The Development of the C Language - Dennis M. Ritchie_](https://www.bell-labs.com/usr/dmr/www/chist.html) : "Off-stack, dynamically-allocated storage is provided only by a library routine and the burden of managing it is placed on the programmer: C is hostile to automatic garbage collection. " – Lundin Nov 24 '21 at 09:38
  • @WeatherVane The book I have focuses on the technical use of pointers, their usefulness. Thanks for the resource, I'll check it! – BillTheKid Nov 24 '21 at 09:42
  • @Lundin Thank you, I'll check it. For now I am left with "we don't know why they needed pointers for memory allocation". – BillTheKid Nov 24 '21 at 09:47
  • 4
    One usefulness of pointers, is that you can pass information around by means of the pointer, rather than the information itself. Like your home address written on paper isn't the house itself, but its location. If there is a large amout of of data, to pass it around you then don't have the overhead of the resources needed to make a copy of that data: you only need to pass the information about where it is (the pointer). It also solves the problem that when the data is modified, it exists only in one place and you don't have to keep track of (and update) the copies that were made. – Weather Vane Nov 24 '21 at 09:48
  • @WeatherVane Wow! It just clicked for me. Thanks a lot, this solves my question for now!! – BillTheKid Nov 24 '21 at 09:52
  • Normally the subject of pointers and their usefulness is a subject to fill four or five chapters in a book of general programming, and the extensions of pointer operators implemented in C to interact with arrays even require more. I think this question is completely out of scope here, and so, I recommend you to read a good book about modern programming and not to ask that here. Thanks. – Luis Colorado Nov 25 '21 at 07:34

2 Answers2

1

malloc does not know what the memory is allocated for. Take for example the memory allocation for vectors. Something like

ptr = malloc(70 * sizeof(int));

You can write some integer numbers there, and later read the same vector as a string for example.

An important usage for pointers is for efficient programming through indirection. Run

#include <stdio.h>

int main()
{
    int ref = 99;
    int *a=&ref;
    int *b=a;
    printf("a:%d b:%d ref:%d\n", *a,*b,ref);
    *a = 100;
    printf("a:%d b:%d ref:%d\n", *a,*b,ref);
    return 0;
}

and see what happens. In large vectors processing applications changing more values at once brings a boost of performance.

Scala
  • 116
  • 2
  • 7
  • We have the option to read an ```int``` variable like a char, even if we allocate it dynamically. Let's say we initialize ```int a = malloc(sizeof(int))```, in that case the allocation does not limit us in the way we could read ```a```. – BillTheKid Nov 24 '21 at 09:56
  • 1
    In this case the allocated memory is not used. – Scala Nov 24 '21 at 10:11
  • You shouldn't cast the result of `malloc`: https://stackoverflow.com/questions/605845 – harper Nov 24 '21 at 10:23
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 24 '21 at 10:24
  • I wanted to show it can be used as integer. I edited the answer to make it clear. – Scala Nov 24 '21 at 10:33
0

C has no other way to differentiate between value types (stored into a memory cell) and reference types (storing a reference to the value). It gets more obvious once you consider structs or arrays, i.e. everything you cannot store into a single memory cell.

int *p = malloc(n*sizeof(int)); 

The above expression would be impossible to translate into a sensible equivalent of your proposed syntax;

int p = malloc(n*sizeof(int)); 

If you abolish the pointer syntax, you have only one option: p contains the memory address of the allocated space (which are coincidentally also integer values). That would mean every pointer (or reference type) variable would be of type int inquire you to cast (and still requiring a referencing operator).

Beltway
  • 508
  • 4
  • 17
  • In the case of an array, whose name is a pointer itself, I understand why we want malloc to return a pointer. In the case of a struct though, we could still say ```struct student {}; struct student p = malloc(sizeof(struct student));```. I cannot locate the problem in this case. – BillTheKid Nov 24 '21 at 09:50
  • 1
    @BillTheKid it is incorrect to say that an array name is a pointer: it isn't. But in some the use of the name *decays* to a pointer to the first element of the array. – Weather Vane Nov 24 '21 at 09:52
  • 1
    `int i` is a value type, `int* i` is a pointer. `student p` implies it is a value type which does not require memory to be freed. You're producing inconsistency while gaining nothing but a slightly simplified syntax. – Beltway Nov 24 '21 at 09:54
  • @Beltway Ok I get it. Now it makes sense! – BillTheKid Nov 24 '21 at 09:58
  • Inconsistency might be phrased poorly: A lot of High-level languages treat all structs/objects as reference types by default with your proposed syntax, but unlike C these don't require you to manage memory by yourself. – Beltway Nov 24 '21 at 10:01