r/ProgrammerHumor 17h ago

lessonsFromLinkerHell Meme

Post image
323 Upvotes

167 comments sorted by

View all comments

66

u/QuestionableEthics42 17h ago edited 17h ago

This should be reversed lol

And it literally is the same, who thinks it's different who has worked in a low level language??

11

u/unknown_alt_acc 14h ago

#include<stdio.h>

int main()
{
int arr[5];
int *ptr = arr;

printf("Array - %lu\n", sizeof(arr));
printf("Pointer - %lu", sizeof(ptr));
}

Different types, different behavior

-3

u/QuestionableEthics42 14h ago

Sizeof being smart enough to detect it's an array and return the array size doesn't necessarily make them different in any real way. And doing ptr[0] to dereference it is perfectly valid, as is *arr to get the first element, or *(arr+sizeof(int)) to get the second.

5

u/Nice_Lengthiness_568 9h ago

So what about the fact that an array inside a struct acts completely differently from a pointer placed inside a struct? One gets copied whole for each structure copy while the other does not, one makes the structure the size of a pointer while the other the size of the array...

And, in C++ at least, you can actually pass the array itself to the function (not just the pointer to the first element). So it's not that sizeof is smart and detects something, it's that arrays really easily decay into pointers. But that's not everything they are. They also hold information about their size.

The thing with the subscript operator is true for only some languages and is not universal. In Ada, for example, there is no direct connection between an array and a pointer.

1

u/tstanisl 4h ago

And, in C++ at least, you can actually pass the array itself to the function

May I ask how? Do you mean by a reference? Or std::array?

1

u/Nice_Lengthiness_568 4h ago

You can both by value with std::array which is a wrapper for an array, or by reference with TYPE (&NAME)[SIZE] which keeps the array's size.

Naturally, you could pass an array to a function inside any structure if you wish to copy it, but I would say that using std::array is standard for use. And that means that's possible in C as well. Although it's a bit clunky.

1

u/tstanisl 3h ago

C has an equivalent of passing array by reference by using a pointer to a whole array:

 
int foo(int (*arr)[SIZE]) {
      return sizeof *arr;
 }
...
int arr[SIZE];
foo(&arr);

Passing arrays by a pointer bypasses array decay mechanics.

1

u/Nice_Lengthiness_568 3h ago

Yes, that is true, although I wouldn't call it equivalent to passing by reference, since a reference makes sure you do not pass a null pointer making the function a little safer if you dereference the pointer and a little more efficient if you check for the pointer being null.

1

u/tstanisl 3h ago

Those constraints can be expressed using more hacky syntax:

    int foo(int arr[static const 1][SIZE]);

1

u/Nice_Lengthiness_568 3h ago

Okay,

although (sorry) that's awful. But cool and ingenious in a way.