Hacker News new | ask | show | jobs
by andrepd 4032 days ago
If you want arrays of variables, you need pointers. It's not enough to know the value of an int (the first element of the array), but you need the pointer to an int (pointer to the first element of the array). Now you can increment the pointer to go to the next element. You couldn't do this with a simple value.

Also, suppose you want to pass a variable of a large data type, like an image, to a function. Instead of copying the entire variable, just pass the cheap pointer. The analogy is giving someone an URL vs the source code of the site for them to paste in the browser (You can't fit the latter onto a QR code, for instance, but you can the former).

1 comments

Of course the problem is, if you're passing a pointer to a data structure to a function, the function doesn't know the size of the data structure unless you pass that as another argument.
You meant to say, "if you're passing a pointer to an array to a function, the function doesn't know the size of the array unless you pass that as another argument".

When passing a (pointer to a) data structure to a function, in 99.99% of cases there's only one data structure you'd pass, and you build this into the function's prototype, e.g.,

  int myfunction( struct my_structure *x )
instead of

  int myfunction( void *x )
and so, yes, the function does know the size of the structure. And in the case of arrays, often it's enough to mark the end of the array (with '\0' in the case of char arrays or NULL in the case of pointer arrays), I'd only roll my sleeves up and worry about minimizing length calculations if I had actually done some profiling and determined that such nitty-gritty optimization was needed (it rarely is).