-1
int Q, A[Q], B[Q];
scanf("%d", &Q);

for(int i=0; i<Q; i++){
    scanf("%d %d", &A[i], &B[i]);
}

for(int i=0; i<Q; i++){
    printf("%d %d\n", A[i], B[i]); //check val
}

if I type
3
1 2
3 4
5 6

the output will be
2 2
4 4
6 6

why? pls help.

  • 2
    Welcome to Stack Overflow. Please read the [About] and [Ask] pages. While you've made a good attempt at including minimal code, you've probably gone a little too far. We really need to see how the variables, especially `A` and `B`, are defined. Please read about how to create an MCVE ([Minimal, Complete, Verifiable Example](https://stackoverflow.com/help/mcve) — or MRE or whatever name SO now uses) or an SSCCE ([Short, Self-Contained, Correct Example](http://sscce.org/)) — the same idea by a different name. – Jonathan Leffler Oct 19 '22 at 05:39
  • In line `printf("%d %d\n", A[i], B[i]); ` it prints the same value twice. It seems A and B are the same. Find out why. – hyde Oct 19 '22 at 05:41
  • I edited my code to show how I declared A and B, but I don't know why A and B prints the same value – kaynan.ghael Oct 19 '22 at 05:45
  • `int Q, A[Q], B[Q];` not good as `Q` has no value assigned yet. Move `int A[Q], B[Q];` til **after** you have scanned a value for `Q`. See https://ideone.com/ubLn24 – Support Ukraine Oct 19 '22 at 05:45
  • BTW: **Always** check the return value from `scanf`. Like: `if (scanf("%d", &Q) != 1) exit(1);` – Support Ukraine Oct 19 '22 at 05:49
  • BTW: Since you are using VLAs (i.e. `int A[Q], B[Q];`) you should check `Q` for a MAX allowed value **before** creating the VLAs. Like `if (scanf("%d", &Q) != 1) exit(1); if (Q > MAX_ALLOWED_Q || Q <= 0) {puts("Illegal Q"); exit(1);}`. I you don't then the user input may result in stack overflow – Support Ukraine Oct 19 '22 at 05:51

1 Answers1

0

just write

    int Q;
    scanf("%d", &Q);
    int A[Q], B[Q];

instead of :

int Q, A[Q], B[Q];
scanf("%d", &Q);

it's a matter of the order of declaration as in your code, you are declaring A and B of unknown size as Q wasn't initialized yet so your code will produce undefined behavior, also begging from C99 standard, you can declare arrays that are created in the stack with size equal to a variable that have a value where that value will be used to initiate the size of the array.

abdo Salm
  • 1,678
  • 4
  • 12
  • 22
  • 1
    Not exactly. C99 defines Variable Length Arrays, but they are an **optional** feature since C11. You can safely use them with clang or gcc, but at least Microsoft compilers do not support it and correctly define `__STDC_NO_VLA__` to advertise that they do not. Said differently, if portability is important, it is better to avoid them... – Serge Ballesta Oct 19 '22 at 06:20