计算二维字符串中的字符数

时间:2014-07-18 08:56:36

标签: c arrays string

Practice.c

#include <stdio.h>

int main(void)
{
  char str[][30]={
                   "My name is Abcd Efgh Jklm.",
                   "I Graduated from BIT.",
                   "I now live in Balochistan."
                 };
  int strcount=sizeof(str)/sizeof(str[0]);
  int i=0;
  int count=0;         

  for(;i<strcount;++i)
  {
    while(str[i][count] != '\0')
      ++count;

    printf("\n\nNumber of Characters in STR[%d] = %d",i,count);
  }

  return 0;
}

上述计划的输出如下:

Number of Characters in STR[0] = 26

Number of Characters in STR[1] = 26

Number of Characters in STR[2] = 26


TEST.C

#include <stdio.h>

int main(void)
{
  char str[][30]={
                   "My name is Abcd Efgh Jklm.",
                   "I Graduated from BIT.",
                   "I now live in Balochistan."
                 };
  int strcount=sizeof(str)/sizeof(str[0]);
  int i=0;         

  for(;i<strcount;++i)
  {
    int count=0;
    while(str[i][count] != '\0')
      ++count;

    printf("\n\nNumber of Characters in STR[%d] = %d",i,count);
  }

  return 0;
}

上述计划的输出如下:

Number of Characters in STR[0] = 26

Number of Characters in STR[1] = 21

Number of Characters in STR[2] = 26


我通过更改变量Test.c的位置对程序count进行了一些修改,并将其放在for loop中,输出符合要求。 我认为count的这种行为是由于它的位置,意味着它的声明位置(在for loop内部或外部)。

我的问题:
1]为什么count放在for loop之外显示26作为所有人的输出?

3 个答案:

答案 0 :(得分:1)

因为Practice.c你只是为第一个字符串递增计数。然后它停留在26 ......

for(;i<strcount;++i)
{
    while(str[i][count] != '\0') //<-- when i == 1 count is already 26
       ++count;
     printf("\n\nNumber of Characters in STR[%d] = %d",i,count);
}

REEDITED :在查阅了一些类似的SO主题之后,我发现C标准规定任何部分完成的数组初始化将为其余元素填充零。所以我之前关于触发未定义行为的代码的评论显然是错误的。 (我想知道我是如何因此而不受惩罚的。)

因此i == 1i == 2 str[i][count] == '\0'以及循环中断。

答案 1 :(得分:1)

因为当你在for循环之外声明它时,你的计数不会重置为0,所以对于你的字符串str [0]你的while循环是有效的。但是在它将输出中的计数值显示为26后,从那时它的值不会重置为0.所以你的内部while循环没有执行str [1]和str [2],并且它直接打印值26,如前所述。

为了做到这一点,你可以在for循环中声明你的计数,或者你也可以在for循环之外声明它,但是在for循环之前将其重置为for循环,如:

for(;i<strcount;++i)   
{
     count = 0; //Reset it to 0
     while(str[i][count] != '\0')
      ++count;

     printf("\n\nNumber of Characters in STR[%d] = %d",i,count);   
}

答案 2 :(得分:0)

Practice.c中,您已在main范围内声明Count。但在Test.c中,您已在Count范围内声明while。每当遇到int count=0时,它会使count为0.对于每个字符串,它将从第0个位置开始计算字符。

但是在Practice.c由于main中的范围,在计算第一个字符串count的长度后保持值为26.因此对于第二个字符串while(str[i][count] != '\0')将失败,因为{ {1}}。因此它将打印值26.对于第三个字符串也将打印相同的值。