在C动态字符数组? [英] Is character array in C dynamic?

查看:180
本文介绍了在C动态字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C.写了一个简单程序的程序输入一个字符串,并与长度一起显示出来。

I have written a simple program in C. A program to input a String and display it along with the length.

#include<stdio.h>

int main()
{
char a[4];
printf("Enter the name : ");
gets(a);

printf("\nThe name enterd is : %s",a);
printf("\nLength of string is : %d",strlen(a));

getch();
return 0;
}

该计划不包含警告或错误。

The program do not contain warning or error.

在运行时我输入值 melwinsunny 作为输入。没有错误,结果显示为:

At run-time I entered the value " melwinsunny " as input. There was no error and the result displayed was :

Enter the name : melwinsunny

The name entered is : melwinsunny

length of string is : 11

为什么会这样呢?我宣布长度为4的字符数组(的一个烧焦[4] 的)。请解释一下。

这是否意味着字符数组是动态的?

推荐答案

还有人指出,这是不确定的行为。这意味着,当你有字符一个[4] 键,您尝试访问任何超出界外(如 A [4 ] ='T'),那么就无法保证你的程序的行为。在某些情况下,它可能工作,而在其他情况下,它可能会崩溃。由于没有保证,所以特别没用依靠这样的code。

Others have pointed out that it is undefined behaviour. What this means is that when you have char a[4] and you attempt to access anything that is out-of-bounds (e.g. a[4] = 't'), then there is no guarantee as to how your program behaves. In some cases, it may work, and in other cases, it may crash. Since there is no guarantee, it is particularly useless to depend on such code.

问题得到()是,你不能告诉它的缓冲区有多大,所以它不知道何时停止写入提供的缓冲区。您可以在11个字符输入,而获得已经执行等价的:

The problem with gets() is that you can't tell it how big the buffer is, so it has no idea when to stop writing to the supplied buffer. You entered in 11 characters, and gets has performed the equivalent of:

a[0] = 'm';
a[1] = 'e';
a[2] = 'l';
a[3] = 'w';
a[4] = 'i'; // at this point, we are writing out-of-bounds
a[5] = 'n';
/* ... etc ... */
a[12] = '\0';

在C,有没有自动边界检查,并有根本没有保证,以会发生什么。

In C, there are no automatic bounds checks, and there are simply no guarantees as to what will happen.

这写入到不能限于通常被认为不安全的缓冲器的功能(除非函数被记录不写超过一定数目的字符,等更多)。

Functions that write to a buffer that cannot be limited are generally considered unsafe (unless the function is documented not to write more than a certain number of characters, etc.).

这篇关于在C动态字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆