这周我一直在努力熟悉 C。我一直在阅读C Primer Plus(第 5 版),但我仍然在变量和指针方面遇到了一些问题。
这是我用来测试的脚本:
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;
}
运行它的输出给了我:
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
问题
这是否char *myvariable=NULL;
意味着这myvariable
是一个指针或一个变量?这个答案说表格char *ptr = "string";
只是向后兼容const char *ptr = "string";
- 真的吗?
- 我在创造一个不变的角色吗?
- 那些不应该是不可变的吗?如果是这样,为什么我可以更新值?
使用函数setvariable(char **myvariable)
- 是**myvariable
“指向指针的指针”吗?
或者myvariable
实际上只是一个字符串(以 nul 结尾的字符数组)?
这是我找到的一些代码(没有文档),所以我有很多关于它的问题。下一个是为什么以myvariable
这种方式定义 - 像以下方式之一那样设置它会不会更好:
char myvariable[] = "apples";
char myvariable[6] = "apples";
我也不明白为什么当setvariable
被调用时它似乎是在传递 myvariable 的地址&
- 传递一个指针不是更好吗?
在询问之前,我曾尝试对此进行研究 - 但两天后进展缓慢,我想要一些建议。
澄清询问
我问的原因是因为从我读过的内容来看,如果某些东西*
后面有一个,char *myvariable
那么它应该是一个指针。
但是,我无法创建一个char
不是指针的指针并分配myvariable
指针指向它。