C字符数组用户输入检查长度

use*_*968 3 c arrays scanf

我读了一个char数组,scanf并想检查长度是否大于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;
}
Run Code Online (Sandbox Code Playgroud)

Set*_*gie 5

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);
Run Code Online (Sandbox Code Playgroud)