gpt4 book ai didi

c - c 中用 "char *"定义的变量是指针还是char类型的变量?

转载 作者:行者123 更新时间:2023-12-04 04:54:19 28 4
gpt4 key购买 nike

这周我一直在努力更熟悉 C。我一直在阅读C Primer Plus (5th Edition) 但是我仍然在使用变量和指针时遇到了一些麻烦。

这是我用来测试的脚本:

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是指针还是变量? This answer说 表格 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指向它的指针。

    最佳答案

    Does char *myvariable=NULL; mean that myvariable is a pointer or a function?


    myvariable是一个指针(即一个变量,因为一个指针是一个变量)。

    1) Is that true?



    我不认为这真的是向后兼容。但是,诸如 "string" 之类的字符串字面量表现为一个常量字符串。

    2) Am I creating a constant character?



    试图修改字符串 "string" 的字符是未定义的行为。没有 const ,因为匿名字符串的类型是 char[] .但程序员经常建议将其声明为 const ,防止出错。

    3) Aren't those supposed to be immutable? If so why can I update the value?



    您不能修改 *myvariable (只要赋值给一个字串),但是可以修改指针 myvariable .

    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) ?


    *myvariable是一个字符串和一个指向 char 的指针.

    顺便说一句,我想你应该阅读 this answer .

    关于c - c 中用 "char *"定义的变量是指针还是char类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16990866/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com