简体   繁体   English

C- GCC编译器中的字符数组

[英]Character arrays in C- GCC compiler

This may seem trivial but I am a newbie to programming. 这看似微不足道,但我是编程的新手。 In case of a string, we are supposed to keep a space reserved for the null character, so a string of size 10 will only give us 9 memory locations to use. 如果是字符串,我们应该为空字符保留一个空间,因此大小为10的字符串将只给我们9个存储位置供使用。 I was wondering whether the same happens when we input letters individually into the array.Can anyone please explain? 我想知道当我们分别向数组中输入字母时是否也会发生同样的情况,有人可以解释一下吗?

C arrays aren't aware of their own size, so there's a standardised convention of using the special character '\\0' to mark the end of a string. C数组不知道其自身大小,因此存在使用特殊字符'\\0'标记字符串结尾的标准化约定。

So if you want to implement your own puts() you can implement it like: 因此,如果您想实现自己的puts() ,则可以像下面这样实现:

int puts(const char *s){
   int i=0;
   while(s[i]!='\0'){
      putc(s[i]);
      i++
   }
   return i;

} }

It's just a language convention, non mandatory because the computer needs it but because the programmers need it. 这只是一种语言约定,不是强制性的,因为计算机需要它,但是因为程序员需要它。 Otherwise you wouldn't know how to stop reading. 否则,您将不会停止阅读。

When you use a character (or any other type), you know how it's size beforehand so there's no need for marking an end of string. 当您使用字符(或任何其他类型)时,您会事先知道其大小,因此无需标记字符串的结尾。

In C, a string basically is an array. 在C语言中,字符串基本上一个数组。 And the size of that array must always be big enough for the terminating null character. 并且该数组的大小必须始终足够大以容纳终止的空字符。 So if I have 所以如果我有

char array[10];

I can do 我可以

array[0] = 'H';

or 要么

array[5] = 'x';

but I had better stop putting in characters at array[8] so I can do 但是我最好停止在array[8]输入字符,这样我就可以

array[9] = '\0';

at the end. 在末尾。

Bottom line: I can do this: 底线:我可以这样做:

array[0] = 'C';
array[1] = 'a';
array[2] = 't';
array[3] = '\0';
printf("%s\n", array);

or this: 或这个:

array[0] = 'S';
array[1] = 'p';
array[2] = 'a';
array[3] = 'g';
array[4] = 'h';
array[5] = 'e';
array[6] = 't';
array[7] = 't';
array[8] = 'i';
array[9] = '\0';
printf("%s\n", array);

but not this: 但不是这个:

array[0] = 'H';
array[1] = 'e';
array[2] = 'l';
array[3] = 'i';
array[4] = 'c';
array[5] = 'o';
array[6] = 'p';
array[7] = 't';
array[8] = 'e';
array[9] = 'r';
array[10] = '\0';    /* XXX WRONG */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM