实践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

测试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内部或外部)。
我的问题是:
1]为什么当置于count之外时,将for loop显示为所有人的输出?

最佳答案

因为在您的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);
}

重新编辑:在查阅了一些类似的SO主题之后,我发现C标准声明,对于剩余的元素,任何部分完成的数组初始化都将填充为零。所以我之前关于这个代码触发未定义行为的评论显然是错误的。(我想知道我是怎么没有受到惩罚的)。
所以对于i == 1i == 2str[i][count] == '\0'循环中断。

关于c - 计算二维字符串中的字符数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24821012/

10-11 04:12
查看更多