简体   繁体   English

数组值在C中突然改变

[英]Array values suddenly changing in C

I'm making a program that has global arrays. 我正在制作一个具有全局数组的程序。 In the function where I assign values to the arrays and print them, everything is fine. 在将值分配给数组并打印它们的函数中,一切都很好。 But as soon as I try to use these arrays in another function, suddenly the values are different. 但是,当我尝试在另一个函数中使用这些数组时,值突然不同。

    int *numeros;
    char *operadores;
    int num, num_operadores;

void crearArray() {

    int i;

    printf("How many numbers?\n");
    scanf("%d", &num);

    numeros = (int*)calloc(num, sizeof(int));
    operadores = (char*)calloc(num - 1, sizeof(char));
    num_operadores = num - 1;

    num += (num - 1);

    for (i = 0; i < num; i++) {

        if(i % 2 == 0 || i == 0) {
            printf("\t\nEnter a number: ");
            scanf("%d", &numeros[i]);
        }
        else {
            fflush(stdin);
            printf("\t\nEnter an operator: ");
            scanf("%c", &operadores[i]);
        }

    }

    printf("Array: ");

    for (i = 0; i < num; i++) {

        if(i % 2 == 0 || i == 0)
            printf("%d ", numeros[i]);

        else
            printf("%c ", operadores[i]);

    }

}


void crearArbol() {

    int i;

    printf("\n\nArrays:\n\t Numbers: ");

    for(i = 0; i < num_operadores + 1; i++)
        printf("\n\t\t Numeros[%d]: %d ", i, numeros[i]);

    printf("\n\t Operators: ");

    for(i = 0; i < num_operadores; i++)
        printf("\n\t\t Operadores[%d]: %c ", i, operadores[i]);

}

int main() {
    crearArray();

    crearArbol();

    return 0;
}

Of course, printing the array wasn't the main purpose for crearArbol but for now there's nothing in there but that and I can't seem to work out why it changes. 当然,打印数组并不是crearArbol的主要目的,但是目前那里什么也没有,但是我似乎无法弄清楚为什么它会改变。

Example output: 输出示例:

How many numbers? 有多少个数字?

3 3

Enter a number: 1 输入数字:1

Enter an operator: * 输入运算符:*

Enter a number: 2 输入数字:2

Enter an operator: / 输入运算符:/

Enter a number: 3 输入数字:3

Array: 1 * 2 / 3 (Printed array from first function crearArray) 数组:1 * 2/3(从第一个函数crearArray打印的数组)

Arrays: Numbers: 数组:数字:

Numeros[0]: 1 Numeros [0]:1

Numeros[1]: 0 Numeros [1]:0

Numeros[2]: 2 Numeros [2]:2

Operators: 运营商:

Operadores[0]: Operadores [0]:

Operadores[1]: * (Printed array values from second function crearArbol) Operadores [1]:*(第二个函数crearArbol中的打印数组值)

Thanks in advance for any help! 在此先感谢您的帮助!

You're writing and reading outside the bounds of the arrays. 您正在数组的边界之外书写和读取。 You're using i to alternately index numeros and then operadores , but that means i is always twice as big as it should be for either array. 您正在使用i交替索引numerosoperadores ,但这意味着对于任何一个数组, i总是两倍大。 You need to divide i by two to convert it into a usable index. 您需要将i除以2才能将其转换为可用索引。

num += (num - 1);

for (i = 0; i < num; i++) {

    if(i % 2 == 0 || i == 0) {
        printf("\t\nEnter a number: ");
        scanf("%d", &numeros[i / 2]);
    }
    else {
        fflush(stdin);
        printf("\t\nEnter an operator: ");
        scanf("%c", &operadores[i / 2]);
    }

}

Rather than doubling num and then alternating access to the two arrays based on whether i is divisible by two, I'd keep num as is and instead access both arrays each loop iteration. 而不是将num加倍,然后根据i是否可被2整除来交替访问两个数组,我将按原样保留num ,而是在每次循环迭代时访问两个数组。

for (i = 0; i < num; i++) {

    printf("\t\nEnter a number: ");
    scanf("%d", &numeros[i]);

    if (i < num - 1)
        fflush(stdin);
        printf("\t\nEnter an operator: ");
        scanf("%c", &operadores[i]);
    }

}

The reason for this behavior is that you are not reading the items into the correct indexes of the array: only indexes 0, 2, 4, ... of numeros have valid data, while indexes 1, 3, 5, ... of oepradores have operators. 出现这种现象的原因是您没有将项目读入数组的正确索引中:只有numeros索引numeros ,...具有有效数据,而numeros索引numeros ,... numeros具有有效数据。 oepradores有操作员。 The remaining indexes have zeros, because you allocated with calloc . 剩余的索引为零,因为您分配了calloc

The first function masks this problem by printing the same indexes that it reads, while the second function exposes the issue by printing "straight" indexes. 第一个功能通过打印与读取的索引相同的索引来掩盖此问题,而第二个功能通过打印“直接”索引来揭示此问题。

Obviously, the reading part is an issue, because it goes past the end of allocated arrays (an undefined behavior). 显然,读取部分是一个问题,因为它超出了分配的数组的末尾(未定义的行为)。 You can fix it by modifying the reading loop to read both the number and the operator in the same go: 您可以通过修改读取循环以一次读取数字和运算符来解决此问题:

// Do not increment num
for (i = 0; i < num; i++) {
    printf("\t\nEnter a number: ");
    scanf("%d", &numeros[i]);
    if (i == num-1) {
        break; // Last number comes with no operator
    }
    fflush(stdin);
    printf("\t\nEnter an operator: ");
    scanf("%c", &operadores[i]);
}

Obviously, you would also need to modify the printing code of crearArray to match that of crearArbol . 很明显,你还需要修改的打印代码crearArray以匹配的crearArbol

Respectfully, the mental error was trying to treat two separate arrays as if a single array. 分别地,精神错误试图将两个单独的数组视为一个单独的数组。 Find an example of an array of structures. 查找结构数组的示例。 Use separate index variables on separate arrays?! 在单独的数组上使用单独的索引变量? A suggestion for compound conditionals: use (()) instead of relying on rules of precedent. 关于复合条件的建议:使用(())而不是依赖先例规则。 I really can not figure your use of fflush on an input stream. 我真的不知道您在输入流中使用fflush。 This also points out the lack of error checking. 这也指出缺少错误检查。
As a general practice, learn how to dump your data from your debugger. 通常,了解如何从调试器中转储数据。 As a source of debug ideas, save the code, then modify and see what happens... 作为调试思路的来源,请保存代码,然后进行修改,然后看看会发生什么...

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

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