简体   繁体   中英

Why malloc returns a pointer? What is the usefulness of pointers?

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!

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.

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, ie 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM