C - Difference between “char var[]” and “char *var”?

后端 未结 4 1199
悲&欢浪女
悲&欢浪女 2020-11-27 06:49

I am expecting that both following vectors have the same representation in RAM:

char a_var[] = \"XXX\\x00\";
char *p_var  = \"XXX\";

But st

相关标签:
4条回答
  • 2020-11-27 07:30

    As others said, char *p_var = "XXX"; creates a pointer to a string literal that can't be changed, so compiler implementations are free to reuse literals, for example:

    char *p_var  = "XXX";
    char *other  = "XXX";
    

    A compiler could choose to optimize this by storing "XXX" only once in memory and making both pointers point to it, modifying their value could lead to unexpected behavior, so that's why you should not try to modify their contents.

    0 讨论(0)
  • 2020-11-27 07:36

    Arrays can be treated (generally) as pointers but that doesn't mean that they are always interchangeable. As the other said, your p_var points to a literal, something static that cannot be changed. It can point to something else (e.g. p_var = &a_var[0]) but you can't change the original value that you specified by quotes....

    A similar problem is when you are define a variable as an array in one file, and then extern-use it as a pointer.

    Regards

    0 讨论(0)
  • 2020-11-27 07:48

    The first creates an array of char containing the string. The contents of the array can be modified. The second creates a character pointer which points to a string literal. String literals cannot be modified.

    0 讨论(0)
  • 2020-11-27 07:49

    At a guess, the function f modifies the contents of the string passed to it.

    0 讨论(0)
提交回复
热议问题