练习.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 == 1
和 i == 2
str[i][count] == '\0'
和循环中断。
关于c - 计算二维字符串中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24821012/