的C指针运算上的字符 [英] C Pointer Arithmetic on Characters
问题描述
我有以下的code,在该行崩溃的我在哪里初始化 CH
:
的char * p =测试;
焦炭CH = * P ++;
的printf(位置:%S \\ N%C,P,CH);
但是以下code没有问题:
的char * p =测试;
焦炭CH = * P ++;
CH ++;
的printf(位置:%S \\ N%C,P,CH);
在第一种情况下,你要修改 T
中的测试字符串编译入程序,这是在你的code未意味着改变存储器的一部分保持(通常;有在那里它允许某些环境中,但通常它是不)。这是因为(* P)++
手段的(严格意义上)的 * p = * P + 1
(例如,获得字符由 p
,增加它,并把它写回),当然, * p
所指向的编译的测试。
你的第二个版本不存在这样的问题,因为你递增 CH
,您的是的允许改变。你的第二个版本实际上增加两个不同的东西,其实,首先它字符CH = * P ++;
这在检索字符* P
键,然后递增<code > p (现在它指向测试中的E),然后你做 CH = CH ++
。 (你可能意味着只是 CH ++;
在那里,因为 ++
直接在其操作数时)
I have the following code that crashes at the line where I am initializing ch
:
char * p = "Test";
char ch = *p++;
printf("Here : %s\n%c", p, ch);
However the following code has no problem:
char * p = "Test";
char ch = *p++;
ch++;
printf("Here : %s\n%c", p, ch);
In the first situation, you're trying to change the T
in the "Test" string compiled into the program, which is held in a part of memory that your code isn't meant to change (usually; there are some environments where it's allowed, but usually it isn't). That's because (*p)++
means (loosely speaking) *p = *p + 1
(e.g., get the character pointed to by p
, increment it, and write it back), and of course, *p
is pointing to the compiled-in "Test".
Your second version doesn't have that problem, because you're incrementing ch
, which you are allowed to change. Your second version actually increments two different things, in fact; first it does char ch = *p++;
which retrieves the character at *p
and then increments p
(now it points to the "e" in "Test"), and then you do ch = ch++
. (You probably meant just ch++;
there, since ++
operates directly on its operand.)
这篇关于的C指针运算上的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!