【问题标题】:Operators and precedence in cc中的运算符和优先级
【发布时间】:2014-11-09 09:32:36
【问题描述】:

我遇到了以下程序。

 #include<stdio.h> 
    int main() 
    { 
      char *s[] = { "knowledge","is","power"}; 
      char **p; 
      p = s; 
      printf("%s ", ++*p); 
      printf("%s ", *p++); 
      printf("%s ", ++*p); 

      return 0; 
    }

输出:nowledge nowledge s 我确定
1.首先printf打印nowledge
2.Second printf 也打印nowledge,因为它包含一个后增量,因此保留了第一个 printf 的原始值。
现在在这个阶段,我很困惑 *p++ 到底做了什么。现在将 p 指向isowledge

【问题讨论】:

  • 我知道输出......但我想知道解释 - @ralph
  • 你为什么不阅读一些关于运算符优先级的文档?您应该学习如何做到这一点,以便您可以对代码进行推理。
  • @ralph 你不是通过反复试验来学习的!

标签: c pointers operators operator-precedence


【解决方案1】:

*p 处的值是 *char 类型 (指针的值是分配了它所指向的类型大小的地址)

增加它会导致该值被添加一个 sizeof(char)

就像这样写:

  printf("%s ", ++(*p)); 

p 的值是 **char 类型

增加它会导致该值添加一个 typeof(*char) 。

区别在于下一个地址中的值持有一个*char 是下一个字符数组的第一个字符的地址

我没有查看优先表(我相信您可以在简单的谷歌搜索中找到) 但是通过运行代码你可以理解 ++ 在 * 之前

如果你想检查它运行这个:

 printf("%s ", (*p)++);

【讨论】:

  • 是的,但是当我递增 p 时,为什么它会跳转到 'is' 而在以上两个 printf 中,它是逐个字符递增的。在第一个 printf 'K' 被省略。那么为什么在第二个 printf 光标跳到下一个字符串'is'之后。
【解决方案2】:
  char *s[] = { "knowledge","is","power"}; // s is an array of pointers
  char **p; // p is a pointer to a pointer to char
  p = s; 
  printf("%s ", ++*p); //(*p) pointing to first string of s, pre-increment so "nowledge" printed
  printf("%s ", *p++); // (*p) printed then post-increment  of p (not *p) hence jumped to next pointer in the array s
  printf("%s ", ++*p); 

【讨论】:

    【解决方案3】:

    这个程序的输出很混乱,因为++*p 增加了p 指向的值,这使得字符串数组s 的不同元素都增加了。

      printf("%s ", ++*p);
    

    *p 返回的值递增。 p 指向 s[0]。因此s[0] 将指向"nowledge"

      printf("%s ", *p++); 
    

    p 仍然指向char * 数组的第一个元素。因为我们之前将s[0] 的值增加了1,所以s[0] 仍然指向"nowledge"p 在取消引用后递增。

      printf("%s ", ++*p); 
    

    *p 返回的值递增。 s[1] 将递增并指向 "s"

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 2013-07-31
      • 2021-03-16
      • 1970-01-01
      • 2013-02-24
      • 2017-06-02
      • 1970-01-01
      • 2013-02-09
      相关资源
      最近更新 更多