DEV Community

Why use pointers at all.

Adam Crockett πŸŒ€ on September 27, 2020

I am very rusty with c, I do try to learn it but every time I get stuck on something. I need to know something that's bugging me. Not what is a pointer, but why? I can have a value but why use it as a pointer? What is the reason and benifits?

Collapse
 
jessekphillips profile image
Jesse Phillips

Could you provide a language you are familiar with where you don't use pointers and I'll explain how it uses pointers (not as a language construct).

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

Sure so my day to day would be spent in Javascript / Typescript.

Collapse
 
jessekphillips profile image
Jesse Phillips

OK so this is harder than I thought. I wanted to use some form of ideomatic code, but I'm not really seeing it. All interactions with objects and array is by reference, much like pointers in C.

If you pass the object to a function, modification within that function will be visible to the parent. But I am not really seeing this approach taken with javascript.

const list = [{Name : 'one'}];
const one = list[0];
one.Name = 'two';
console.log(list);
Enter fullscreen mode Exit fullscreen mode

C does not have reference types. If javascript was passing objects by value, the list would not see the modification.

struct Item {
 Β  Β string name;
} 
void main()
{
 Β  Β const list = [Item("one")];
 Β  Β Item one = list[0];
 Β  Β one.name = "two";
 Β  Β assert(list[0].name == "one");
} 
Enter fullscreen mode Exit fullscreen mode

Using D shows the behavior without "pointers". Now if you asked why use pointers in D, my answer would be to interface with C. There are other uses, but it is not frequent enough to try and cover.

Thread Thread
 
pentacular profile image
pentacular

The javascript semantic are like the C semantics here because neither of them pass by reference.

An object value in javascript allows you to reach the properties associated with that object value in a similar way that a pointer allows you to reach the elements of the array that it indexes into.

In both languages there is only pass by value semantics.

const a = (v) => { v = [1] };
let i = [0];
a(i);
// i is [0], because javascript passes by value
void a(int *b) { b = malloc(sizeof (int[1])); }
void test() {
  int *p = 0;
  a(p);
  // p == 0, because c passes by value.
}
Thread Thread
 
jessekphillips profile image
Jesse Phillips

I understand that, array in C isn't a great example because they are pointers. However this still fits well with answering the question, "why use pointers"

I provided another example using struct the point was this could be extrapolated into the C and Javascript languages, because this is where you'll see javascript behavior differ from C.

Thread Thread
 
adam_cyclones profile image
Adam Crockett πŸŒ€

Sorry this post kind of exploded and so there is so much information to go through, il have a good read later on today 😁

Collapse
 
moopet profile image
Ben Sinclair

The simplest use case is passing things by reference.
Say you have a string like, "hello my name is Bob", and you want to make it all capitals?
It's fine to send that string over to a function in its entirety, wait for it to be tinkered with and copy it back.
But say you have something bigger, like an image, potentially a gigabyte in size, and you want to send it over to a function that finds the brightest colour in it? You don't want to be copying all that information across every time, so you use a pointer to tell the function, "here's my image, use it directly".

Pointers also allow you to do other stuff like links in linked lists or have variables of indeterminate size or even to directly change something on the display (what they call "memory mapping") and a few other tricks.

Collapse
 
jvarness profile image
Jake Varness

Pointers also allow you to keep references to multiple variables of the same type, kind of like an array, except with the help if malloc, calloc, and realloc you can point to as many variables of the same type as you want, provided the memory still has space to allocate.

Pointers enable you to have things like Strings in your C code (in the form of char*) since Strings aren’t native to C.

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

Let's check my loose understanding of char. char represents an integer type uint8 from 0 - 255 which is somehow synonymous with utf8 encoding. char* is somehow array like of chars by reference?

I think malloc does direct allocation of a value to memory? Not sure about the rest.

Thank you, This is fun!

Thread Thread
 
jvarness profile image
Jake Varness

You’re right on the money with chars, malloc doesn’t necessarily allocate a value, it allocates a segment of memory for that pointer based on how many bytes you tell it to allocate. This is why sizeof is an extremely important function to use when working with pointers, because it tells you how large any variable or struct is in bytes. If you wanted to make a pointer that was large enough to hold X amount of any type, you’d want to allocate X * sizeof(type) for that pointer, and you would want to advance it by sizeof(type) to get to the next thing it points to.

Pointers are what make me not like programming in C because it’s where a lot of very common problems can happen: segmentation faults happen a lot and the same code that might run fine on one OS might not behave the same on another.

Collapse
 
pentacular profile image
pentacular

I think it's important to note that passing a pointer by value is not pass by reference.

Passing the pointer by value grants the means to reference the thing pointed at on the other side, but it doesn't have pass-by-reference semantics.

e.g., this code can't change the value of p, so bar will always receive a null pointer value.

{
  int *p = 0;
  foo(p);
  bar(p);
}

If p were passed by reference then the value of p could be changed by the call to foo.

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

That makes sense, an image would be like 4 channels of uint8 so yes that's a lot of data. What happens if I pass the string "hello world" into a function not as a pointer, does the function create a copy in memory.

Collapse
 
unchar1 profile image
Askara Novaru • Edited

In most cases you don't. Pointers are usually a bit further down the ladder of abstraction. Languages like Java, Python, JS, do use pointers internally, but you as a user don't really need to worry about it. Knowing about pointers is helpful in the sense that you'll have a better grasp of how things work "under the hood", but you can make do without knowing them.
NOTE: Reference types are NOT pointers, though they are implemented USING pointers, they're a lot less flexible (in a good way) and it's a lot harder to shoot yourself in the foot with them

Collapse
 
secure_daily profile image
Artem

For low level programming (drivers development), you might want to have a value stored at specific address. Although you will probably use a combination of pointers, and special linker/compiler instructions.
In general though, it is hard to write c code without pointers. Just passing stuff around would be tough.

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli • Edited

So you can say, to your great grandkids, as they're writing in AmazonMongoose4000

I remember when computers had to be told how to manage their memory or they'd try and reach out of their allocated stack space and overflow.
Kids today using the yottaHz megacores with exabytes of RAM, you got it easy. With your mind reading development environments and your petabit peer to peer wetware.
You'll never know what it's like to accidentally point to something off the heap and get a segfault. Malloc, free, new, delete, they're like foreign words to you. When I was your age I had to be careful with my resources.
I miss those days. Before we were required to upload our consciousnesses to HyperGlobalMegacorp, when I could close my eyes. πŸ‘΄

Collapse
 
sgkul2000 profile image
Shreesh Kulkarni

There are multiple reasons for using a pointer. I will give you some :

  • preventing making copies of data. using a pointer to alter data alters the original data instead of creating new copies fo the data.
  • Using complex structures of data. Using pointers can facilitate the use of complex data structures like stacks, queues, and linked lists.
  • Pointers can be used to pass arrays and strings to functions these are a few advantages that practically make sense and I have used pointers for the above reasons itself. if you need more information or you wanna discuss then feel free to do so.
Collapse
 
albertalvarez profile image
Albert

For example, pointers allow to β€œreturn” arrays from functions (de name of an array is a pointer to the first element of the array). They also allow abstraction; you can pass a pointer to a function in drivers development to abstract hardware layer.

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

Ahhh I see, the quotation marks are important because we don't actually return the array, the body of the function defined the array, then placed it into memory? And so now we can access that spot in memory by it's address, I guess you could even get the size of the array and other such things.