gpt4 book ai didi

c - (C) 输入后字符数组大小发生变化?

转载 作者:行者123 更新时间:2023-11-30 20:38:18 25 4
gpt4 key购买 nike

以下有什么区别? (三)

char x[100] ;
char y[] = ""; // no space between the double quotations
char z[] = " "; // space between the double quotations

如果用户在数组 y 中输入了一个输入,例如“test”,它的大小是否会更改为 5?

char y[] ="";
gets(y); // user entered "test"

如果用户在数组 x 中输入了大于 100 的输入,它的大小会改变吗?

char x[100] ;
gets(x); // user entered an input larger than 100
<小时/>

以及为什么此代码有效:(如果用户输入“test”,它将打印“test”)

#include<stdio.h>
#include<string.h>
int main(){
char name[] = " " ; // space between the double quotations
gets(name);
for(int i=0 ; i< strlen(name) ; i++) {
printf("%c",name[i]);
}
return 0 ;
}

而这个没有? (这个打印奇怪的符号)(如果用户输入“test”,它将打印“t”和一个笑脸符号)

#include<stdio.h>
#include<string.h>
int main(){
char name[] = "" ; // no space between the double quotations
gets(name);
for(int i=0 ; i< strlen(name) ; i++) {
printf("%c",name[i]);
}
return 0 ;
}

这个让我抓狂,它没有循环就可以工作,即使双引号之间没有空格

#include<stdio.h>
#include<string.h>
int main(){
char name[] = "" ; // no space between the double quotations
gets(name);
printf("%c",name[0]);
printf("%c",name[1]);
printf("%c",name[2]);
printf("%c",name[3]);
return 0 ;
}

即使双引号之间没有空格,这个也可以使用 (puts) :

#include<stdio.h>
#include<string.h>

int main(){
char name[] = "" ;
gets(name);
puts(name);
return 0 ;
}

最佳答案

不,数组的大小没有调整。

它之所以有效,是因为行为是未定义的,而可能发生的事情之一就是它有效。

当您这样做时,您的写入超出了数组的范围,根据非法写入位置的数据,会发生不同的情况。

永远不要使用gets(),因为它不能防止缓冲区溢出,而这正是你的程序正在做的事情,你应该使用fgets()函数,它的大小为数组作为参数,以防止将超过该大小的字节写入数组

fgets(array, sizeOfTheArray, stdin);

可以防止出现问题,并且代码不会像您认为的那样“工作”。

此外,c 中的字符串不会将其大小存储在任何地方,因此像您一样调用 strlen() 是不好的,这

for(int i=0 ; i< strlen(name) ; i++)
/* ^ do not do this */

导致性能不佳,您可以像这样存储值

size_t length = strlen(name);
for(int i = 0 ; i < length ; i++)

或者,使用 c 字符串是非 nul 字节序列后跟一个 nul 字节的事实,如下所示

for(int i = 0 ; name[i] != '\0' ; i++)

关于c - (C) 输入后字符数组大小发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29491349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com