C语言计数器

标签 c arrays int sizeof

我主要是一名电子硬件人员,但我从 friend 那里学到了 D 的基础知识,所以我决定选择一种更标准的语言,比如 C。所以,任何建议都会很好。 基本上,我使用整数“phew”作为计数器,来反转所有数字。 super 基本,但我很难找到在 C 中执行此操作的方法。我的代码:

#include <stdio.h>

int main()
{
     int input;
     int phew;
     printf("Binary Number: ");
     scanf("%d", &input);
     while(phew < sizeof(input))
     {
          if(input[phew] == 0)
               printf("1");
          else
               printf("0");
          phew++;
      }
      return 0;
}

编译器错误是:

helloworld.c: In function ‘main’:
helloworld.c:11:11: error: subscripted value is neither array nor pointer nor vector
if(input[phew] == 0)
        ^

最佳答案

首先,在下面的声明中,

 while(phew < sizeof(input))
  • 调用undefined behaviorphew是一个自动局部变量且未初始化。您需要初始化phew喜欢 int phew = 0;

  • 在这种情况下,sizeof(input)有效,但没有任何意义。

也就是说,您只能使用 []数组类型上的运算符。在你的情况下,inputint ,所以你不能写 input[n] .

详细说明,引用 C11标准,第 §6.5.2.1 章

Syntax

postfix-expression [ expression ]

和描述

One of the expressions shall have type pointer to complete object type, the other expression shall have integer type, and the result has type type.

所以,很明显,在你的情况下input不是“类型指针”,因此会出现错误。

解决问题,

  1. 您可以更改 input 的类型如char input[32] = {0};

  2. 将扫描语句更改为 `scanf("%29s", input);

  3. 添加while(phew < strlen(input))

有道理。您将需要string.h头文件。查看 strlen() here的详细信息.

你必须像这样改变它

while(phew <  strlen(input) )
 {
      if(input[phew] == '0')  //ASCII 48, decimal
           printf("1");
      else
           printf("0");
      phew++;
  }

关于C语言计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34877834/

相关文章:

c - 如何检查 DES key 的奇偶校验?

没有名称的 C++11 STL 容器数组

arrays - F# - 什么是数组<'T>?

mysql - 为什么 mysql explain show using index prefer bigint column than int column

将字节数组转换为整数

C 将文字 char '0' 转换为 int 0(零),如何?

c - C中的服务器客户端程序

c - 实现push和pop的单链表-seg fault

c++ - OpenCV:C++ 和 C 性能比较

Javascript:将字符串数组解析为具有自定义键名称和值的对象