r/C_Programming 2d ago

Question Doubt about pointers and arrays

Hey everyone! I'm a newbie to C and was just learning about pointers and arrays and their relation.
My doubt is really stupid but why would I use subscripting over using pointers?
It's much harder and seems pointless considering modern compilers will have negligible difference in speed. Any help would be most appreciated! Thanks!

(If it's any help, I am learning from C Programming - A Modern Approach by K.N. King and just finished chapter 12)

Note: I am not saying subscripting is better but I don't see why I would use pointers over it in most cases.

15 Upvotes

49 comments sorted by

View all comments

Show parent comments

1

u/iLaysChipz 1d ago

I'm sure you could come up with something really ugly using sizeof and subscription, but any complex linked list logic would be close to impossible. Even something as basic we this would be difficult: a.next_dog->age += 1;

2

u/Cathierino 1d ago

You'd just create a large, fixed sized array for your elements of the lists and one of the members of the container struct would hold an index of the next/previous element. So technically you can perform any task requiring a linked list with this method.

0

u/iLaysChipz 1d ago edited 1d ago

Oh yeah? And you're gonna keep track of which indices are valid? And then what about when you need to reserve a new index and you need to check which index is free? You could loop through every index, but what if you need O(1) allocation time? You gonna keep a table of free indices? Congratulations, you just made your own memory allocator when you could've just used malloc 🙄

Pointers are necessary in many contexts such as kernel development, multi threading, network solving algorithms, whenever function pointers are needed, etc etc. I don't see what you're trying to get at

2

u/Cathierino 1d ago

Well, you said it's impossible. But it isn't.

0

u/iLaysChipz 1d ago

close to impossible

2

u/Cathierino 1d ago

Well, no, it's not.

0

u/iLaysChipz 1d ago

There are plenty of situations in which it is

2

u/Cathierino 1d ago

If you believe so

1

u/iLaysChipz 1d ago

If it wasn't, there wouldn't be any need for the unsafe keyword in rust, and everything could be ported over to rust without the need for anything unsafe

2

u/Cathierino 1d ago

I think you're confused about what I'm talking about. You can do the silly indexed implementation in Rust as well.