c - 基于 C 中另一个字符数组的奇怪长度和内容

标签 c arrays

我有一个充满字母和空格的字符数组(最大长度为 100),我想创建另一个具有相同长度的字符数组。如果原始数组中有空格,这个新数组应该在特定位置包含空格,如果有字母,则为“#”。 我需要这个用于 c 中的刽子手游戏并以这种方式解决它:

//the original array is in a structure (with other char arrays)
//struct entry{
//char expression[100];
//....
//};

//which an array of called dictionary is created and filled later (this works)



//now the part where it somehow fails:

//figure out the length of the string in the first char array
int oldlength = strlen(dictionary[index].expression);

//create the new array (same length) and set its memory to 0 (doesn't actually matter)
char newexp[oldlength];
memset(newexp, 0, oldlength * sizeof(char));

//fill this new array as described
for(int i = 0; i < oldlength; i++)
{
    if(dictionary[index].expression[i] == ' ')
    {
        newexp[i] = ' ';
    }
    else
    {
        newexp[i] = '#';
    }
}

现在我认为这个新阵列会按照我想要的方式工作。有时确实如此,在这种情况下,我的刽子手游戏完全可以正常工作。但有时它似乎使新数组比旧数组更长并添加奇怪的字符(或者可能只是空格(?)的奇怪输出)。

现在我的测试方法是:

printf("Expression in struct: %s\n", dictionary[index].expression);
printf("Length of expression in struct: %d\n", oldlength);
printf("Expression afterwards in new array: %s\n", newexp);
printf("Length of expression in new array: %d\n", strlen(newexp)); //I know, int != size_t

现在有时游戏可以运行并且输出类似于:

Expression in struct: wonderful
Length of expression in struct: 9
Expression afterwards in new array: #########     //9x '#'
Length of expression in new array: 9

注意:“//9x '#'”不在输出中,我只是计算它们以便更快地理解(在下一个示例中相同)

但有时它会给出这样的东西(实际的,德国的例子):

Expression in struct: glaesarn
Length of expression in struct: 8
æ@pression afterwards in new array: ########     //yes, 8x '#'
Length of expression in new array: 11

在这个例子中,我稍后又给出了第二个数组,它说:

æ@######     //6x '#' ?

试了几次...有时开头会加这两个字母..有时最后会加其他东西:

//another example

Expression in struct: Moebelrolle
Length of expression in struct: 11
æ@pression afterwards in new array: ######### ░h=v        i=væÚ7v     //9x '#' ?
Length of expression in new array: 27

//and later the arrays gives out
æ@######### ░h=v        i=væÚ7v     //9x '#'?

我不明白这两个数组怎么会突然有如此不同的长度(没有其他同时访问它),我认为这段代码相对简单。 这也让我感到困惑,“之后的表达式”的输出如何变成“之后的 æ@pression”……这怎么可能?

最佳答案

看来你需要改变:

char newexp[oldlength];

收件人:

char newexp[oldlength + 1];

并将空终止符\0放在newexp的末尾。

关于c - 基于 C 中另一个字符数组的奇怪长度和内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34099229/

相关文章:

c - 使用输入字符串并逐字符打印出来

基于 c 中的 EBP 从堆栈帧调用函数及其参数

c++ - 动态内存分配给 char 数组

arrays - 将两个字符串数组组合成一个矩阵

c++ - 字符数组和指针的基本混淆

javascript - 如何访问返回的数组对象

c - 试图确保字符串缓冲区是一个合理的人名

c++ - 使用消息在 ROS 上发送 C 数组

c - 从目标文件中提取一个部分以分隔 .o

javascript - 获取平均返回 NAN - JS