我对字符串文字的分配/存储感兴趣.
我确实在这里找到了一个有趣的答案,说:
定义内联字符串实际上是将数据嵌入程序本身并且无法更改(某些编译器通过智能技巧允许这样做,不要打扰).
但是,它与C++有关,更不用说它不打扰了.
我很烦.= d
所以我的问题是我的字符串文字保存在哪里以及如何保存?我为什么不试着改变呢?实施是否因平台而异?有没有人愿意详细说明"聪明的伎俩"?
C中字符串文字的类型是什么?是char *或const char *否const char * const?
那么C++呢?
在以下规则中,当数组衰减到指针时:
左值[见2.5问题]型阵列的-T出现在表达衰变(有三个例外)转换成一个指向它的第一个元素的; 结果指针的类型是指向T的指针.
(例外情况是,当阵列是的sizeof或&运算符的操作数,或为字符数组一个文本字符串初始化.)
如何理解数组是"字符数组的文字字符串初始值设定项"的情况?请举个例子.
谢谢!
int main()
{
char *x = "HelloWorld";
char y[] = "HelloWorld";
x[0] = 'Z';
//y[0] = 'M';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在上面的程序中,HelloWorld将处于只读部分(即字符串表).x将指向该只读部分,因此尝试修改该值将是未定义的行为.
但是y将在堆栈中分配HelloWorld并将被复制到该内存中.所以修改y将正常工作.字符串文字:指针与字符数组
这是我的问题:
在下面的程序中,都char *arr和char arr[]使段错误,如果内容被修改.
void function(char arr[])
//void function(char *arr)
{
arr[0] = 'X';
}
int main()
{
function("MyString");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请分享您的知识.
当我执行下一个代码时
int main()
{
char tmp[] = "hello";
printf("%lp, %lp\n", tmp, &tmp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到了相同的地址。但对于下一个代码,它们会有所不同
int main()
{
char *tmp = "hello";
printf("%lp, %lp\n", tmp, &tmp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您能解释一下这些示例之间的内存差异吗?
我是 C 新手,无法理解指针。我感到困惑的部分是关于char *和int *。
比如我们可以直接给char赋值一个指针,比如
char *c = "c"; 它不会出错。
但是,如果我像刚才那样为 int 分配一个指针,例如int * a = 10;,
它会出错。我需要在内存中留出额外的空间来为 int 分配一个指针,
像int *b = malloc(sizeof(int)); *b = 20; free(b);……
谁能告诉我为什么?
数组被视为常量指针,因此我们无法更改指针值,我无法想象我们假设 -
a[5]="hello";
a="hai"; // I Know This not possible but why if below a[0]='a' is possible?
a[0]='a' ;//this is possible because a is store in stack memory.
Run Code Online (Sandbox Code Playgroud)
现在来指针
char *a="hello";
a="hai"; //i know this is possible because string are store in code section which is read only memory then why it is changed?
a[0]='a' //Not possible because it is store in stack and string is store in code section if above a="hai" is possible then why a[0]='a' is not …Run Code Online (Sandbox Code Playgroud) 向所有程序员问好,我无法理解一些东西
char a[]="hello"
char* b="salam"
第一个问题是为什么我们不能修改 2,例如b[0]='m',我知道 2 被存储为编译时常量但我不明白它是什么意思以及 2 的 quiddity 是什么?
第二个问题:
3.
char a[]="hello";
char* c=a;
c[0]='r';
Run Code Online (Sandbox Code Playgroud)
现在我们可以修改然后打印c,但是我们不能修改 2 !为什么?
我无法理解这些指针的概念,请向我解释