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

后端 未结 4 1228
悲&欢浪女
悲&欢浪女 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.

提交回复
热议问题