0

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;
}```
1
  • 3
    Your arrays are size zero. They don't get sized retroactively. Commented Jan 8, 2020 at 20:51

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.