Why can’t I dereference pointers in strcpy() like I do with other variables?

0
0
Asked By MellowDolphin42 On

I'm a bit confused about why I don't need to dereference pointers when using `strcpy()` in C. Normally, when I'm assigning values to pointers, I use the `*` operator, but it seems like I don't have to do that with strings when using `strcpy()`. Is there a specific reason for this? Also, how do you all manage to remember these kinds of memory rules in C? Is there a technique to grasp the concepts of memory allocation and dereferencing better?

3 Answers

Answered By LogicWhale88 On

Exactly! `strcpy()` needs a pointer to where the string starts, and if you dereference like `*s`, you'll just be passing a single character instead of the whole string. Think of it as giving `strcpy` the address of where to copy from, not the content itself.

MellowDolphin42 -

Got it! So pointers in C are less about individual values and more about their locations. Thanks!

Answered By CleverOtter99 On

What you might be missing is that every time you call `strcpy`, it's actually manipulating the data at the pointers behind the scenes. When you write `strcpy(s, "Hello")`, `s` is already a pointer to the first character, so you don't need to dereference it. Dereferencing is done internally by `strcpy` itself! It's all about giving it the address to start copying from, not the value at that address.

CuriousBeetle21 -

So, just to clarify, `strcpy()` handles the dereference for me, which is why I can just pass the pointer and not worry about using `*`, right?

Answered By ThoughtfulTurtle37 On

In C, there's no built-in string type. Instead, we just pass pointers to the first character of the string. `strcpy()` works with those pointers directly! If you passed a dereferenced pointer, you'd lose access to the rest of the string since it just gives you the first character instead of the string itself. There's a logic to how C manages memory and how pointers work for strings!

CharmingBison77 -

That makes sense! C behaves differently than languages with native strings. I think I’m starting to understand.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.