Still learning more C and am a little confused. In my references I find cautions about assigning a pointer that has not been initialized. They go on to give examples. Great answers yesterday by the way from folks helping me with pointers, here:
Precedence, Parentheses, Pointers with iterative array functions
On follow up I briefly asked about the last iteration of the loop and potentially pointing the pointer to a non-existent place (i.e. because of my references cautioning against it). So I went back and looked more and find this:
If you have a pointer
int *pt;
then use it without initializing it (i.e. I take this to mean without a statement like *pt= &myVariable
):
*pt = 606;
you could end up with a real bad day depending on where in memory this pointer has been assigned to. The part I'm having trouble with is when working with a string of characters something like this would be ok:
char *str = "Sometimes I feel like I'm going crazy.";
Where the reference says, "Don't worry about where in the memory the string is allocated; it's handled automatically by the compiler". So no need to say initialize *str = &str[0];
or *str = str;
. Meaning, the compiler is automatically char str[n];
in the background?
Why is it that this is handled differently? Or, am I completely misunderstanding?
Pointers are powerful because they allow you to directly access memory addresses. This same usefulness also makes them very dangerous. If you don't use your pointers correctly you can access garbage data or leave them dangling. Another product of incorrect usage is memory leaks.
int *p = malloc(sizeof(int)); Here, we have allocated enough memory to store a single integer and returned the address of that space to be assigned to the pointer p . Now, the only way to work with that space is through the pointer.
Pointers save memory space. Execution time with pointers is faster because data are manipulated with the address, that is, direct access to memory location. Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as well.
In this case:
char *str = "Sometimes I feel like I'm going crazy.";
You're initializing str
to contain the address of the given string literal. You're not actually dereferencing anything at this point.
This is also fine:
char *str; str = "Sometimes I feel like I'm going crazy.";
Because you're assigning to str
and not actually dereferencing it.
This is a problem:
int *pt; *pt = 606;
Because pt
is not initialized and then it is dereferenced.
You also can't do this for the same reason (plus the types don't match):
*pt= &myVariable;
But you can do this:
pt= &myVariable;
After which you can freely use *pt
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With