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

标签 c arrays string

练习.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循环中,输出符合要求。 我认为 count 的这种行为是由于它的位置,意味着它被声明的位置(在 for 循环 内部或外部)。

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

最佳答案

因为在您的 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' 和循环中断。

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

相关文章:

c++ - 从搜索算法返回的约定 - 索引或迭代器

c - 对 `__ubsan_handle_nonnull_arg' 的 undefined reference

c - 我们如何在 C 的作用域之外访问 auto 和 static 变量?

在与我的 C++ 类相同的 Visual Studio 解决方案中从 C 项目(共享库)调用 C 函数,出现链接器错误

JavaScript 对象数组分解为 PHP 数组

C++:将CSV文件读入结构数组

c - C 中的回文子串排序器

c++ - 为什么我不能删除字符串的数字字符?

c - 在 JSFL 中调用 dll 的问题

java - 我的程序出现错误