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
作为所有人的输出?
答案 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 == 1
和i == 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.对于第三个字符串也将打印相同的值。