Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can a pointer do that a variable can't do?

Tags:

c

pointers

I'm learning about pointers and have been told this: "The purpose of pointers is to allow you to manually, directly access a block of memory."

Say I have int var = 5;. Can't I use the variable 'var' to access the block of memory where the value 5 is stored, since I can change the value of the variable whenever I want var = 6;? Do I really need a pointer when I can access any variable's value just by using its variable, instead of using a pointer that points to the address where the value is stored?

like image 967
Carefullcars Avatar asked Sep 27 '15 08:09

Carefullcars


1 Answers

"The purpose of pointers is to allow you to manually, directly access a block of memory."

This is not always true. Consider

*(int*)(0x1234) = some_value;

this is "direct" memory access. Though

int a = some_value, *ptr = &a;
*ptr = some_other_value;

you are now accessing a indirectly.

Can't I use the variable 'var' to access the block of memory where the value 5 is stored, since I can change the value of the variable whenever I want var = 6; ?

Surely; but the semantics is different.

Do I really need a pointer when I can access any variable's value just by using its variable, instead of using a pointer that points to the address where the value is stored?

No, you don't. Consider the first example: within the scope where a has been declared, modifying its value through ptr is rather pointless! However, what if you are not within the scope of a? That is

void foo(int x)
{
     x = 5;
}

int main(void)
{
    int x = 10;
    foo(x);
}

In foo, when you do x = 5, there is an ambiguity: do you want to modify foo::x or main::x? In the latter case that has to be "requested" explicitly and the fact that happens through pointers -or, better, through indirection- is a coincidence and a language choice. Other languages have others.

like image 181
edmz Avatar answered Nov 03 '22 18:11

edmz