30 ms·
> I always thought [] was just syntactic sugar over a regular pointer, but seems like I was wrong. For another example showing their differences, if a.c has:
by kbp 8y ago
> I always thought [] was just syntactic sugar over a regular pointer, but seems like I was wrong.
For another example showing their differences, if a.c has:
int n[] = { 1 };
And b.c has:
extern int *n;
printf("%d\n", *n);
Then running b.c will segfault, whereas if it said extern int n[], it would work as expected (hint: extern int n and printf("%d\n", n) would also work). Arrays degrade to pointers at the drop of a hat, but they're distinct from them.
- jcelerier 8y ago> Then running b.c will segfault why would it not ? On one side you declare an int array of size 1, on the other side you declare a pointer. Think about what's going on with the bytes : int n[] = { 1 }; will look exactly the same in memory than int n = 1; which is of course not compatible with int* n = 1; Arrays by themselves have no indirection in C. => https://godbolt.org/g/xwT7uW https://godbolt.org/g/xwT7uW
- kbp 8y agoRight, that's what I was explaining. A lot of people get tripped up by this because arr is equivalent to &arr, int arr[] is equivalent to int *arr as a formal parameter, etc, so many people go around with the idea that arrays are just pointers in C, like in the comment I quoted; it's an easy thing to get confused by. I was giving an example to demonstrate how they differ.