我正在尝试使用取消引用运算符手动增加指向字符串的指针,就像我在下面的 while 循环中看到的那样。它适用于第一个字符,但是当我尝试像在 while 循环中那样手动增加指针时,它不起作用并且我得到了垃圾。有人可以告诉我我不明白的地方吗?此代码按我预期的方式工作。
char *pointToString = "some string or something";
printf("%c\n", *pointToString); // this returns the letter 's'
while(*pointToString != '\0'){
printf("%c", *pointToString);
*pointToString++;
}
这有效并打印出“s”,然后是字符串“some string or something”,但是如果我手动递增它,为什么我不能访问字符串的第二个元素?当我这样做时,我得到垃圾。
printf("%c\n", *pointToString+1);
这将返回字母“o”以外的内容。我也试过这个,但还是有垃圾:
printf("%c\n", *pointToString+sizeof(char));
我不确定这是否正确,但我想我正在递增一个指针,就像我在 while 循环中所做的那样:
*pointToString++;
那为什么我不能自己做呢?
最佳答案
不能使用表达式访问下一个元素
printf("%c\n", *pointToString+1);
因为一元运算符*
的优先级高于二元运算符+
。首先,访问当前字符;然后,将 1
添加到其中。正确使用括号可以解决这个问题:
printf("%c\n", *(pointToString+1));
关于c - 当我将指针递增 1 时,为什么不能访问字符串中的下一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25705841/