I've been working hard to get more familiar with C this week. I've been reading C Primer Plus (5th Edition) but I'm still having a bit of trouble with variables and pointers.
Here is my script that I'm using to test:
int main (int argc, char **argv) {
char *myvariable=NULL;
myvariable = strdup("apples");
myvariable = strdup("value updated");
printf("========== \n\n");
printf("this is the thing : %p \n", myvariable);
printf("this is the thingval: %s \n", myvariable);
setvariable(&myvariable);
printf("after function - this is the thing : %p \n", myvariable);
printf("after function - this is the thingval: %s \n", myvariable);
return 0;
}
int setvariable(char **myvariable) {
*myvariable = strdup("value from function");
return 1;
}
Output from running it gives me:
this is the thing : 0x7fee9b4039c0
this is the thingval: value updated
after function - this is the thing : 0x7fee9b4039d0
after function - this is the thingval: value from function
Questions
Does char *myvariable=NULL;
mean that myvariable
is a pointer or a variable? This answer says The form char *ptr = "string";
is just backwards compatibility for const char *ptr = "string";
- Is that true?
- Am I creating a constant character?
- Aren't those supposed to be immutable? If so why can I update the value?
With the function setvariable(char **myvariable)
- is **myvariable
a "pointer to a pointer" ?
Or is myvariable
actually just a string (nul terminated array of characters) ?
This is some code that I've found (no documentation) so I have a lot of questions about it. The next one is why is myvariable
defined this way - and would it not be better to set it up like one of these ways:
char myvariable[] = "apples";
char myvariable[6] = "apples";
I also don't understand why when setvariable
is called it appears to be passing in the address of myvariable with &
- wouldn't it be better to pass a pointer?
I've tried to do research on this before asking - but after two days progress has been slow and I'd like a little advice.
Clarification for Asking
The reason I'm asking is because form what I've read it looks like if something has a *
after it, like char *myvariable
then it should be a pointer.
However, I am having trouble creating a char
that is not a pointer and assigning the myvariable
pointer to point to it.