【问题标题】:Arrays are not storing values in the loop数组不在循环中存储值
【发布时间】:2020-01-08 20:49:48
【问题描述】:

那是我的 C 代码。我正在尝试使用 for 循环将值存储在我的数组中,但没有存储任何内容,只有变量 trackingCodes 的值发生变化。我不知道错误来自哪里。没有编译错误

#include <stdio.h>

int main(void) {
int trackingCodes = 0;
char typeCode[trackingCodes];
int codeLength [trackingCodes];
int byteChar = 0;
int byteInt = 0;
int byteDouble = 0;
int j = 0;
int totalBytes = 0;
int totalByteDouble = 0;
int totalByteInt = 0;
int totalByteChar = 0;


scanf("%d", &trackingCodes);

for ( j = 0; j < trackingCodes; j++)
{
    scanf("%d %c", &codeLength[j], &typeCode[j]);
    if (typeCode[j] == 'c')
    {
        byteChar = codeLength[j] * sizeof(char);
        totalByteChar = totalByteChar + byteChar;

    }
     else if (typeCode[j] == 'i')
    {
        byteInt = codeLength[j] * sizeof(int);
        totalByteInt = totalByteInt + byteInt;

    }
     else if (typeCode[j] == 'd')
    {
        byteDouble = codeLength[j] * sizeof(double);
        totalByteDouble = totalByteDouble + byteDouble;

    } 

}

    totalBytes = totalByteChar + totalByteDouble + totalByteInt;
    int t = 0;

    for(t = 0; t < trackingCodes; t++){
        if(codeLength[t] != 'i' && codeLength[t] != 'c' && codeLength[t] != 'd'){
            printf("Invalid Tracking code type");
            return 0;
        }
    }

    printf("%d bytes\n", totalBytes);



    return 0;
}```

【问题讨论】:

  • 您的数组大小为零。它们不会追溯调整大小。

标签: c arrays for-loop


【解决方案1】:

您需要移动数组定义,使其在您阅读trackingCodes 之后。通过这种方式,您可以创建一个具有扫描大小的可变长度数组。喜欢:

scanf("%d", &trackingCodes);

char typeCode[trackingCodes];
int codeLength [trackingCodes];

并且...始终检查来自scanf 的返回值——即:

if (scanf("%d", &trackingCodes) != 1)
{
    // error handling
}

【讨论】:

    【解决方案2】:

    我想你认为代码:

    int trackingCodes = 0;
    char typeCode[trackingCode];
    

    将无限期地将typeCode 的大小绑定到trackingCodes 的值。它实际上会用trackingCodes当前值 的大小来声明typeCode

    解决方案是从stdin 扫描您的输入,如@4386427 的回答中所述,或者使用动态内存管理分配它(malloc/free 等)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2012-08-20
      相关资源
      最近更新 更多