简体   繁体   English

C编程初学者 - 请解释这个错误

[英]C programming beginner - Please explain this error

I'm just starting off with C and was trying out a few examples from Ritchie's book. 我刚刚从C开始,正在尝试Ritchie的书中的一些例子。 I wrote a small program to understand character arrays, but stumbled on some errors, and was hoping for some insight on what I've understood wrong: 我写了一个小程序来理解字符数组,但偶然发现了一些错误,希望对我所理解的错误有所了解:

#include <stdio.h>
#define ARRAYSIZE 50
#include <string.h>

main () {
  int c,i;
  char letter[ARRAYSIZE];
  i=0;
  while ((c=getchar()) != EOF )
  {    
    letter[i]=c;
    i++;
  }
  letter[i]='\0';
  printf("You entered %d characters\n",i);
  printf("The word is ");

  printf("%s\n",letter);
  printf("The length of string is %d",strlen(letter));
  printf("Splitting the string into chars..\n");
  int j=0;
  for (j=0;j++;(j<=strlen(letter)))
    printf("The letter is %d\n",letter[j]);
}

The output is: 输出是:

$ ./a.out 
hello how are youYou entered 17 characters
The word is hello how are you
The length of string is 17Splitting the string into chars..

What is happening? 怎么了? Why isn't the for loop giving any output? 为什么for循环不提供任何输出?

The syntax should be; 语法应该是;

for (j=0; j<strlen(letter); j++)

Since strlen is costy operation, and you don't modify the string inside the loop, it's better to write like: 由于strlen是costy操作,并且你不修改循环内的字符串,所以最好这样写:

const int len = strlen(letter);
for (j=0; j<=len; j++)

Besides, it's strongly recommanded to always check for buffer overflow when working with C-strings and user-input: 此外,强烈建议在使用C字符串和用户输入时始终检查缓冲区溢出:

while ((c=getchar()) != EOF && i < ARRAYSIZE - 1)

The error is in the for, simply swap the ending condition and the increment like this: 错误在for中,只需交换结束条件和增量,如下所示:

for (j = 0; j <= strlen(letter); j++)

Question: what's that last character? 问题:最后一个角色是什么?

for (j=0;j++;(j<=strlen(letter))) it's not correct. for (j=0;j++;(j<=strlen(letter)))这是不正确的。

It should be for (j=0; j<=strlen(letter); j++) - increment at the third position. 它应该是for (j=0; j<=strlen(letter); j++) - 在第三个位置递增。

The correct format of for loop is: for循环的正确格式是:

for (initialization_expression; loop_condition; increment_expression){
    // statements
}

so your for loop should be 所以你的for循环应该是

for (j = 0; j < strlen(letter); j++)

In the for loop, the condition is i++, which evaluates to false (0) the first time. 在for循环中,条件是i ++,它第一次计算为false(0)。 You need to swap them: for (j=0; j <= strlen(letter); j++) 你需要交换它们: for (j=0; j <= strlen(letter); j++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM