简体   繁体   English

在C中使用不同的数值获得相同操作的不同长度

[英]Getting different lengths for the same operation with different number values in C

I have 2 for-loops which populate arrays with letters from the alphabet. 我有2个for循环,其中使用来自字母表的字母填充数组。 I have a lowercase array set, and an uppercase array set. 我有一个lowercase数组集和一个uppercase数组集。 The problem is when I initialize the arrays with the letters, the lengths are coming back different. 问题是当我用字母初始化数组时,长度返回的不同。

char uppercase[26];
char lowercase[26];
int indexUpper = 0;
int indexLower = 0;


// Get uppercase array:
for(int a = 65; a <= 90; a++){
    uppercase[indexUpper] = a;
    indexUpper++;
}

// Get lowercase array:
for(int b = 97; b <= 122; b++){
    lowercase[indexLower] = b;
    indexLower++;
}

printf("UPPERCASE = %lu\n", strlen(uppercase));
printf("LOWERCASE = %lu\n", strlen(lowercase));

$=> UPPERCASE = 26
$=> LOWERCASE = 27

I apologize if this is a no brainer. 如果这是没有道理的,我深表歉意。 I am truly trying to learn and comprehend the C language and its rules. 我确实在尝试学习和理解C语言及其规则。 Thanks to all who contribute. 感谢所有贡献者。

strlen() reads the character array as long until it finds a NUL byte ( '\\0' , numerical value zero). strlen()读取字符数组,直到找到一个NUL字节( '\\0' ,数值为零)为止。 Your arrays don't contain any, since you haven't assigned one there. 您的数组不包含任何数组,因为您尚未在其中分配一个数组。

That means that strlen will continue reading past the end of the array , which is illegal, and the resulting behaviour is not defined . 这意味着strlen将继续读取超过数组末尾的值 ,这是非法的,并且未定义结果行为。 Getting a 27 is rather mild, you could be getting arbitrary numbers, or your program could crash. 获得27相当温和,您可能会获得任意数字,否则您的程序可能会崩溃。

If you want to use strlen() , you should explicitly assign a NUL byte at the end of the string, and of course allocate space for it. 如果要使用strlen() ,则应在字符串末尾显式分配一个NUL字节,当然还要为其分配空间。

Perhaps something like this: 也许是这样的:

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

int main(void)
{
    char upper[27];
    int i;
    for (i = 0 ; i < 26; i++) {
        /* This only works in a character set where the letters
           are contiguous */
        upper[i] = 'A' + i;
    }
    /* i == 26 now */
    upper[i] = '\0';
    printf("len: %u\n", (unsigned) strlen(upper));
    return 0;
}

(Though using strlen here at all seems somewhat pointless, since you already know the number of items in those arrays.) (尽管在这里使用strlen似乎毫无意义,因为您已经知道这些数组中的项目数。)

When using strlen the char array must be nul terminated - but yours isn't so you have undefined behavior. 使用strlen ,char数组必须以nul终止-但是您的数组不是,因此您有未定义的行为。

To print the size of the arrays try: 要打印数组的大小,请尝试:

printf("UPPERCASE = %zu\n", sizeof uppercase);
printf("LOWERCASE = %zu\n", sizeof lowercase);

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

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