简体   繁体   English

我在c中访问错误的(越界)char数组索引

[英]Am i accessing wrong (out of bounds) char array Index in c

Suppose we have a character array in c like, 假设我们在c中有一个字符数组,

char a[20];

Can we access index 20 to put terminating NULL like this. 我们可以访问索引20来像这样终止NULL。

a[20]='\0';

But in my algo. 但在我的算法中。 ("which is integer to char array converter") this is necessary to put terminating NULL if last index is,smaller then the size of char array for example, (“这是整数到字符数组转换器”)如果最后一个索引是小于char数组的大小,这是必要的,例如,

If size of my int is 4 ("1421") then i have to put '1' at index 0, '4' at index 1, '2' at index 2 and '1' at index 3. 如果我的int的大小是4(“1421”)那么我必须在索引0处放置'1',在索引1处放置'4',在索引2处放置'2'并且在索引3处放置'1'。

And finally terminating NULL at index 4 最后在索引4处终止NULL

index=4;
a[index]='\0';

Another way to fix the same code, 另一种修复相同代码的方法,

if(index<20)  (Will increase one condition)
    a[index]='\0';

But i just wanna know is it possible......to put terminating NULL at index 20. 但我只是想知道是否可能......将终止NULL置于索引20处。

OK I GOT THIS EVERYONE THANK-U VERY MUCH FOR YOUR HELP. 好吧,我感谢所有人,非常感谢你的帮助。

An array char a[20] has space for 20 characters, at indexes 0 through 19. Writing to a[20] is writing outside the array and will have unpredictable consequences. 数组char a[20]在索引0到19中有20个字符的空间。写入a[20]是在数组外部写入并且会产生不可预测的后果。 You are limited to 20 characters including any terminating NULL character. 您限制为20个字符, 包括任何终止 NULL字符。 If you need space for 20 characters plus a terminating NULL, you need to declare your array as char a[21]; 如果你需要20个字符的空间加上一个终止NULL,你需要将你的数组声明为char a[21]; . Also, declaring a[20] does not put a NULL anywhere. 另外,声明a[20]不会在任何地方放置NULL。

char a[20] : 20 means you can have elements from 0-19 . char a[20] :20表示你可以拥有0-19之间的元素。 and it's assumed that you will use only upto 19.if you fill upto 20 then you will get an error. 并且假设您将仅使用最多19个。如果您填写最多20个,那么您将收到错误。

change it to : 将其更改为:

a[20+1] => a[21] now you can use 20 to put \\0 . a[20+1] => a[21]现在你可以使用20来放置\\0 a[20]='\\0'

Code for @AnkeshKushwah @AnkeshKushwah的代码

int main()
{
char arr[4]="hell";  
printf("%c",arr[4]); // here you will see garabage. 
printf("%c",arr[5]); // here is the terminating character. after 4.
char arr[]="hell";   
printf("%c",arr[4]); // here you will see terminating character.Because hell will take 
                        0-3 and 4 contains \0 
getch();
}

Consider initializing your char array with all zeroes: char a[20] = { 0 }; 考虑使用全零来初始化char数组: char a[20] = { 0 };

That way, no matter how many chars you write (up to 19), you're always null terminated. 这样,无论你写多少个字符(最多19个),你总是无效终止。

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

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