代码片段为:
char c[]="gate2011";
char *p=c;
printf("%s",p+p[3]-p[1]);
The output is: 2011
有人能解释一下它是怎么来的吗?
-----提前感谢-----
代码片段为:
char c[]="gate2011";
char *p=c;
printf("%s",p+p[3]-p[1]);
The output is: 2011
有人能解释一下它是怎么来的吗?
-----提前感谢-----
依次通过每一行:
char c[] = "gate2011";
让我们假设阵列c位于存储器地址200处。
char *p = c;
p现在是指向c的指针。因此它指向存储器地址200。p的实际内容是“200”,表示内存地址。
printf("%s", p + p[3] - p[1]);
当我们把p当作指针对待时,它的值是200。然而,我们也可以把它当作一个数组。p[3]获取字符串中第4项的值,即“e”。C将字符存储为ASCII值。“e”的ASCII值为101。
接下来,我们得到p[1]的值。p[1]==“a”,ASCII值为97。将这些替换为函数:
printf("%s", 200 + 101 - 97);
其评估结果为:
printf("%s", 204);
在存储器地址204处,我们有字符串“2011”。因此,程序打印“2011”。
我不知道你为什么要做这样的事情,但无论如何,这就是正在发生的事情。
p + p[3] - p[1]
这里取一个指针的值,将位置3处的char值相加,然后减去位置1处的char的值。在进行加法和减法运算之前,字符值被隐式转换为数值。
如果是1 000个地点,则将支付1 000+101(e)-97(a)美元。 因此,结果是发现1004个记忆器。 <>>印本/>中的百分数则以该地点开始的体格为准,并以特殊性质终止。 因此,扼杀实际上被拖到“2011年”(头4封信由于101-97=4而丢失)。
如果这仍然没有意义,我建议您仔细研究一下C中的数组是如何工作的。
你期待什么?为什么不呢?
p[3]-p[1] = e - a = 4
p+4 = "2011"
I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...
The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?
I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...
I tried to print all the possible combination of members of several vectors. Why the function below doesn t return the string as I expected? #include <iostream> #include <vector> #...
I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...
I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??
Is there a PHP string function that transforms a multi-line string into a single-line string? I m getting some data back from an API that contains multiple lines. For example: <p>Some Data</...
I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...