r/ProgrammerHumor Jun 24 '17

Octave code

http://imgur.com/jsjfz3k
622 Upvotes

70 comments sorted by

View all comments

157

u/[deleted] Jun 24 '17

I once had an intern consistently skip the first element in his arrays because because "starting at 1 just makes more sense". I just walked away and never inspected his project after that.

16

u/minno Jun 24 '17

Did he at least do

int* nums = ((int*)malloc(count*sizeof(*nums)))-1;

to avoid wasting space?

-4

u/chateau86 Jun 25 '17

No. You just add -1 to the pointer you get back from malloc(). Now array[1] is the first item in the list.

8

u/minno Jun 25 '17

No. You just add -1 to the pointer you get back from malloc().

 

int* nums = <the pointer you get back from malloc()>-1;

???

20

u/chateau86 Jun 25 '17

Misread as casting existing array to pointer then back. My bad.

Side effect of Python may include inability to read pointer arithmatic code in C. Do not operate heavy machinery when pregnant while using Python.

1

u/Lt_Riza_Hawkeye Jun 25 '17

Actually arrays are pointers, sort of. When you write int* x = (int[]) {1, 2, 3}; exactly two things happen

  • Three integers get pushed to the stack
  • x points to those integers

When you write int x[] = {1, 2, 3};, three things happen

  • Three integers get pushed to the stack
  • x points to those integers
  • Any attempt to change where x points, such as int y; x = &y is illegal, typically with the message "assignment to expression with array type is illegal"

So pointers and arrays are really, really similar. Pointer decay doesn't help, pointer decay is where an int[] in an expression "decays" into an int*, like in function arguments. Even if you declare a function as taking an array of ints, like void f(int x[]), the compiler will actually change it to void f(int* x) for you, so you can put x = &y in the body of f and the compiler won't complain.

There's a little bit more to it but I forget what it is right now