Tchunche
Tchunche

Reputation: 43

Arrays are not storing values in the loop

That's my C code. I'm trying to store values in my arrays using the for-loop but nothing is stored and only the value of the variable trackingCodes changes. I don't where the errors comes from . No compiling errors

#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;
}```

Upvotes: 0

Views: 120

Answers (2)

Govind Parmar
Govind Parmar

Reputation: 21542

I think you think the code:

int trackingCodes = 0;
char typeCode[trackingCode];

Will indefinitely bind the size of typeCode to the value of trackingCodes. It's actually going to declare typeCode with the size of the current value of trackingCodes.

Solutions are to either scan your input from stdin as covered in @4386427's answer, or to allocate it with dynamic memory management (malloc/free and co.)

Upvotes: 0

4386427
4386427

Reputation: 44274

You need to move the array definition so that it is after you have read trackingCodes. In this way you create a Variable Length Array with the size scanned. Like:

scanf("%d", &trackingCodes);

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

And... Always check the return value from scanf - that is:

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

Upvotes: 2

Related Questions