gpt4 book ai didi

C 字符数组用户输入校验长度

转载 作者:太空狗 更新时间:2023-10-29 16:08:57 24 4
gpt4 key购买 nike

我用 scanf 读取了一个 char 数组,想检查长度是否大于 15。它只是有时有效。 (如果不是我得到一个错误 --> 核心转储。)

我的代码:

#include <stdio.h>

int checkArray(char string[], int length) {
int i;
for(i=0; string[i] != '\0'; i++);
if(i > length) {
return -1;
}
return 0;
}

int main ()
{
const int length = 15;
char x[15];
scanf("%s", x);
if(checkArray(x, length) == -1) {
printf("max. 15 chars!");
return 1;
}
return 0;
}

最佳答案

x 永远(合法地)不能超过 14 个字符,因为您将它放在大小为 15 的缓冲区中(14 个字符空格,一个用于 NUL 终止符),所以它毫无意义尝试检查它是否少于 15 个字符。

如果您尝试在其中存储一个大于 14 的字符串,它会溢出数组并可能导致像您遇到的那样的错误。 (可选)使您的数组更大,以便它实际上可以容纳超过 15 个字符,并为 %s 放置一个宽度说明符:

char x[30];

scanf("%29s", x); // read a maximum of 29 chars (replace 29 if needed
// with one less than the size of your array)

checkArray(x, 15);

关于C 字符数组用户输入校验长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8511227/

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