3 ms·
Coming from Java, I didn't understand the point of pointers (no pun intended) until I was re-reading through chapter 1 of K&R C. At one point, they mention how
by dbh937 14y ago
Coming from Java, I didn't understand the point of pointers (no pun intended) until I was re-reading through chapter 1 of K&R C.
At one point, they mention how when you pass a variable into a function, it only passes the value really, "copying" the variable, in a way. Then they go on to say that changing the original variable is talked about in chapter 5, which covers pointers. Then it just clicked. If you want to change the original value, pass a pointer to said variable. If you want to just use the value of a variable, pass the variable through the function.
It's so much easier than what I was doing before, assigning the variable to the return value of a function.
- EvaPeron 14y agoSeriously, "true that", and that is why although most of my "day jobs" deal with Java, C is cooler, lol.
- Jach 14y agoI'd stick with avoiding passing pointers unless you really need to change more than one parameter within the function or unless you have a "large" data structure or unless you're using C++ and passing objects around, then you want to avoid the copy constructor and destructor. (Java passes all objects by pointer-value.) I'd also recommend getting in the "const pointer" habit, because then anyone (or compiler) reading your code can be guaranteed you aren't going to change things passed to your function.