[英]what is wrong with my understanding of strings ie character arrays ending with '\0' element in C programming
I am a total beginner and recently started studying strings in C programming. 我是一个初学者,最近开始研究C编程中的字符串。
I understand that we need to supply the '\\0'
(null) character at the end of the string (to act as a end of string marker). 我知道我们需要在字符串的末尾提供
'\\0'
(空)字符(以用作字符串标记的末尾)。 So if my character array is 所以如果我的字符数组是
char string[]={'H','E','L','L','O','\0'};
This makes it a 6 element array. 这使其成为6个元素的数组。
So I was going through this simple example of copying one string to another string. 因此,我正在研究将一个字符串复制到另一个字符串的简单示例。 Here is the code.
这是代码。
#include<stdio.h>
int main()
{
char string1[80],string2[80];
int i;
printf("Enter a string \n");
gets(string2);
for(i=0; string2[i]!= '\0';i++)
{
string1[i]=string2[i];
}
string1[i]='\0'; /*here is my problem*/
printf("The copied string is \n");
printf("%s",string1);
printf("\n");
printf("The number of character are \t");
printf("%d \n",i);
}
why isn't it string1[i+1]='\\0'
?? 为什么不是
string1[i+1]='\\0'
? I mean, isn't by putting string1[i]='\\0'
overwrite the last element that was just stored in the above for loop? 我的意思是,不是通过将
string1[i]='\\0'
覆盖上面存储在for循环中的最后一个元素吗?
The code is correct, because of the way the for
loop works: 该代码是正确的,因为
for
循环的工作方式:
for(A; B; C)
CODE;
Is equivalent to: 等效于:
A;
while (B)
{
CODE;
C;
}
(Except for the use of continue
, that will jump to the increment expression, not the condition, as it would happen with a while
). (除了使用
continue
,它将跳转到增量表达式,而不是条件,如while
会发生)。
And since the loop ends when string2[i] != '\\0'
, it is obvious that upon exiting, i
is the index for the proper NUL
byte. 并且由于循环在
string2[i] != '\\0'
,因此很明显在退出时, i
是正确的NUL
字节的索引。 So after that: 所以之后:
string1[i] = '\0';
will write the \\0
at the same place as it is in string2
. 将
\\0
与string2
中的相同位置写入。
Usually for this kind of analysis it is helpful to think about preconditions
and postconditions
. 通常,对于这种分析,考虑
preconditions
和postconditions
是有帮助的。 That is, assuming there are no break
and no goto
, you are guaranteed that at the beginning of a for
or while
loop the condition is always true
. 也就是说,假设没有
break
也没有goto
,可以保证在for
或while
循环的开始条件始终为true
。 And just after the end of a for
or while
loop the condition is always false
. 在
for
或while
循环结束后,条件始终为false
。
Your particular code, illustrated with assert
calls: 您的特定代码,用
assert
调用说明:
for(i=0; string2[i] != '\0'; i++)
{
asssert(string2[i] != '\0');
string1[i] = string2[i];
}
asssert(string2[i] == '\0');
string1[i] = '\0';
Looking at the code, it seems as if i is incremented as long as the character is not '\\0'. 查看代码,只要字符不是'\\ 0',就好像我是递增的。 So, the last time it's incremented, it increments to a new position that hasn't had a character written to it yet.
因此,上次递增时,它将递增到尚未写入字符的新位置。
So, at the end of the loop, there's a space to write the null character to. 因此,在循环结束时,有一个空格可以写入空字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.