0

if i have a 2D array

int A[3][2] = { {3,4}, {5,6}, {0,-5} }

what will be the result if I try to print the element A[1]? will it be garbage value? or will it become a logical error?

6
  • 1
    Technically C doesn't have multi-dimensional array. What you have with A is an array of arrays of int. So A[1] is an array (of two int values). If the compiler will complain or if it's a logical error depends on the context, what you do with the array. Commented Nov 26, 2021 at 13:13
  • so if I try to print the value of A[1], what would be the result of it? garbage? Commented Nov 26, 2021 at 13:19
  • @Someprogrammerdude, technically C does not have negative numbers but only unary minus followed by numerical literal Commented Nov 26, 2021 at 13:19
  • @TerryTan, it depends on how you try to print it. There are ways that would produce perfectly valid, well-defined results, and ways that would produce undefined behavior. Commented Nov 26, 2021 at 13:20
  • Note also that the program producing undefined behavior does not necessarily mean it would yield output that you would recognize as "garbage". Commented Nov 26, 2021 at 13:22

1 Answer 1

1

Assuming you do something like

printf("%d\n", A[1]);

then that will be undefined behavior. That's because the array A[1] will decay to a pointer to its first element (i.e. in that context A[1] will decay to &A[1][0]), and the %d format specifier is wrong for printing pointers.

However

printf("%p\n", (void *) A[1]);

will be perfectly fine, as %p is the correct format specifier to print void * pointers.


And as noted in a comment, just because you have undefined behavior that doesn't mean the program will crash or result it "garbage" (even though the (possibly truncated) pointer might look like that when printed as a decimal integer).

Sign up to request clarification or add additional context in comments.

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.