本文介绍了在 C 中初始化一个 char 指针.为什么被认为是危险的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
char s有什么区别[] 和 C 中的 char *s?

我初始化了一个 char 指针:

I initialize a char pointer:

char *a="test";

我在某些地方读到这被认为是只读,而且很危险.

I have read at some places that this is considered read-only and that it's dangerous.

这是否意味着 "test" 没有在堆中分配空间?这是否意味着字符串test"可以稍后在程序中被覆盖?

Does that imply that the "test" is not allocated space in the heap? Does that mean that the string "test" can be written over later in the program?

---扩展我的问题---

如果我像上面那样初始化了 a 然后我做了一堆其他的初始化,比如:

If I have initiliazed a as above and then I do a bunch of other initializations like:

int b=20;
char c[]="blahblahblah";

内存中的test"可以被20"或blah"覆盖吗?还是这种情况没有根据?

Can "test" in memory get overwritten with "20" or "blah"? Or does that scenario have no ground?

推荐答案

这很危险,因为字符串是不可修改的.尝试这样做会导致未定义的行为.

This is dangerous because the string is not-modifiable. Attempting to do so results in undefined behavior.

所以最好这样做:

const char *a = "test";

您是正确的,在这种情况下 "test" 没有分配在堆或堆栈*上,而是位于不可修改的静态内存中.

You are correct that "test" in this case is not allocated on the heap or the stack* and instead lies in static memory that is not-modifiable.

*标准没有提到堆栈或堆,尽管它通常是这样实现的.

*The standard says nothing about the stack or heap, though that's how it's usually implemented.

另一方面:

char a[] = "test";

修改是安全的,因为它只是以下的缩写:

Is safe to modify since it's just short-form for:

char a[] = {'t','e','s','t',''};

这是一个普通的可修改数组.

which is an ordinary modifiable array.

这篇关于在 C 中初始化一个 char 指针.为什么被认为是危险的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:24