0

Here's my code

#include <stdio.h>
#include <math.h>
int main()
{

    int d, a[3][3] = {{2, 4, 5}, {6, 7, 8}, {9, 10, 11}};
    for (d = 0; d < 5; d++)
    {
        printf("a[%d] = %d\n\n", d, a[d]);
    }
    return 0;
}

i'm getting the output

a[0] = 6422048
a[1] = 6422060
a[2] = 6422072
a[3] = 6422084
a[4] = 6422096

i'm curious about where did those values come from, and why is it incrementing by 12?

1
  • it's technically UB for d == 4 and so on Commented Apr 9, 2021 at 15:11

3 Answers 3

2

They are pointers. AND the outputs are increased by 12 next because size of int[3] is 12 bytes.

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

1 Comment

... and using %d to print the pointers isn't correct. %p should be used.
1

a is array of arrays, when you are trying to output you are printing array. Arrays are like pointers, it will give you an address of array. Another problem is, you are accessing your 2D array like 1D array, your array is 3x3 matrix but you are accessing to its 3th and 4th index with d variable. What you want to do is:

    for (int i = 0; d < 3; ++j) {
        for(int j = 0; j < 3; ++j)
            printf("a[%d][%d] = %i\n\n", i, j , a[i][j]);
    }

3 Comments

I'm not so much into C, but I don't think arrays "are like pointers" in C. I think they decay into pointers when passed as arguments to functions, like printf, but, I could be wrong. Anyway, +1.
@TedLyngmo actually you are right, I just wanted to tell that by printing array will give you an address like in pointers.
I get that. I don't know C well enough to say that the address of the array is guaranteed. printf has expectations. %d and a pointer ... not a perfect match. In my world, that's undefined behavior. Perhaps not in C.
0

If you compile with -Wall -Wextra (always do that) you'll get the answer:

$ gcc k.c -Wall -Wextra
k.c: In function ‘main’:
k.c:9:26: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘int *’ [-Wformat=]
    9 |         printf("a[%d] = %d\n\n", d, a[d]);
      |                         ~^          ~~~~
      |                          |           |
      |                          int         int *
      |                         %ls

It says that a[d] has type int* which means that it's a pointer.

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.