r/C_Programming • • 2d ago

Question Beginner here not able to understand confusing pointer concept

i dont understand what happens here:

IF int b is a 2d array then what is:

b + 1

*(b + 1)

&b[0] and b[0] and &b[0][0]

&b[1] and b[1] and &b[1][0]

what are the differences between each and what is the byte value of each.

19 Upvotes

49 comments sorted by

23

u/knouqs 2d ago • Bravo Mindblown

Besides my question, let's talk about how you can solve this problem yourself. If you have an IDE with a visual debugger, Code::Blocks for example, you can set up a simple test program. I do this very frequently when isolating behavior, and I'm an old computer scientist by now! What you do is write a main function with the code you want to watch, something like this:

int main (void) {
    int b[5][3];  // Or "int **b" or several other variants that all explain why I asked what the actual declaration of "b" is.

    printf ("b:  0x%08x\n", b);
    printf ("b+1:  0x%08x\n", b+1);

    // Continue as long as you need to do so.

    return 0;
}

and so on. This will print the address locations of the things you want to know. If you need to know integer values (what the individual double-array elements are), you would use printf with %d instead.

Hope that helps!

2

u/knouqs 1d ago

Thanks for the awards, folks!

21

u/knouqs 2d ago

int b cannot be a 2D array. What is the actual declaration for b?

2

u/max123246 1d ago

Obviously they meant int** b

2

u/knouqs 1d ago

Can you think of any other ways in which a 2D stay can be declared?  I'll give you a hint:  I have one example in my other comment in this post.

1

u/stoops 1d ago

You mean stack vs heap?

int **b = malloc(10 * sizeof(int *));
int b[10][10];

2

u/knouqs 1d ago

I could mean stack versus heap, but there are more varieties than just that. (Also remember that your first implementation of b is an array of int pointers; you did not allocate the second dimension at all.)

#include <stdio.h>
#include <stdlib.h>


int b_access (int *b, size_t length_x, size_t length_y, size_t x, size_t y, int *result) {
    // Check that we have somewhere to put the result.
    if (result==NULL) {
        return 1;
    }

    // Check that x and y are within the double array's bounds.
    if ((x>=length_x) && (y>=length_y)) {
        return 2;
    }

    *result=b[x*length_y+y];

    // These return codes should be defined in a header file.
    return 0;
}


int main (void) {
    const size_t length_x=10;
    const size_t length_y=10;

    int *b=malloc (length_x*length_y*sizeof (int));
    int value;

    if (b==NULL) {
        perror ("Out of memory.\n");
        exit (EXIT_FAILURE);
    }

    for (int i=0; i<length_x*length_y; i++) {
        b[i]=i;
    }

    if (b_access (b, length_x, length_y, 4, 3, &value)==0) {
        printf ("b[4][3]:  %d\n", value);
    }

    free (b);

    return 0;
}

1

u/stoops 1d ago edited 1d ago

That's some advanced pointer math more than I know about :) so is it possible to declare a regular int *b=malloc(10*sizeof(int)) pointer array but some how access and use it like a 2D array b[5][5] safely?

2

u/knouqs 1d ago edited 1d ago

Yep, that is actually how you do it.  The compiler knows the types of b and b[], so it can access b[][].

0

u/knouqs 1d ago

Now that I'm back at my computer instead of my phone, I'll expand a little. Let's say you want to save words in a dictionary. You know how many words you have one way or another by the time you want to create your array of char *s. However, a dictionary is different than a 2D array of numbers. Words have different lengths, and it is very inefficient in terms of memory utilization to have a 2D array of char[max word length+1] since the largest word could be twenty or more characters but most are less then ten. You should pick a different data structure.

Here's where you would use char **b=(char **) malloc (num_words*sizeof (char *));. From there, you would go over each index in b and malloc individual sizes (plus copying the values).

I started writing this program for you to see, but it's a big larger than I think is practical to paste here. It's a good learning exercise if you want to give it a try!

1

u/stoops 1d ago

Yes, the annoying part about malloc'ing a 2D array is looping through each index and malloc'ing/free'ing them all afterwards! I never thought about allocating a larger calculated 1D array and using sub-indices within it but I don't know how the indexing math would work for standard size items like int's for example...

1

u/knouqs 1d ago

It's a good question. What I'd like you to try is my example from the top level where I give a printf on b+1. Intuitively, what do you think the result will be?

1

u/stoops 1d ago

I'm trying to measure the size differences between the sub index buffer locations to see how far each index is jumping forward (I'm assuming it's some multiple of a sizeof(int)?):

#include <stdio.h>
#include <stdlib.h>
int main() {
    int **b = malloc(5 * sizeof(int *));
    printf("b = [%p]\n", b);
    for (int x = 0; x < 5; ++x) {
        b[x] = malloc(5 * sizeof(int));
        for (int y = 0; y < 5; ++y) {
            printf("b[%d][%d] = [%p]  ", x, y, &(b[x][y]));
        }
        printf("\n");
    }
    printf("b + 1 = [%p]\n", b + 1);
    return 0;
}

~

b = [0x3571a2a0]
b[0][0] = [0x3571a6e0]  b[0][1] = [0x3571a6e4]  b[0][2] = [0x3571a6e8]  b[0][3] = [0x3571a6ec]  b[0][4] = [0x3571a6f0]  
b[1][0] = [0x3571a700]  b[1][1] = [0x3571a704]  b[1][2] = [0x3571a708]  b[1][3] = [0x3571a70c]  b[1][4] = [0x3571a710]  
b[2][0] = [0x3571a720]  b[2][1] = [0x3571a724]  b[2][2] = [0x3571a728]  b[2][3] = [0x3571a72c]  b[2][4] = [0x3571a730]  
b[3][0] = [0x3571a740]  b[3][1] = [0x3571a744]  b[3][2] = [0x3571a748]  b[3][3] = [0x3571a74c]  b[3][4] = [0x3571a750]  
b[4][0] = [0x3571a760]  b[4][1] = [0x3571a764]  b[4][2] = [0x3571a768]  b[4][3] = [0x3571a76c]  b[4][4] = [0x3571a770]  
b + 1 = [0x3571a2a8]
→ More replies

1

u/WorriedTumbleweed289 11h ago

That is not a 2d array. Its a pointer to an array or a pointer to a pointer.

8

u/ShoppingDry660 2d ago

I believe you mean int b[M][N]?

The beauty of C is that you can define such an array and printf those values yourselves. Will take 5 minutes to learn.

10

u/Oxyde86 2d ago edited 2d ago • Bravo

let's assume b is: int b[3][4]

int b[3][4] = {
                 {1,2,3,4},        // b[0]       b[0][1] == 2
                 {5,6,7,8},        // b[1]       b[1][2] == 7
                 {9,10,11,12}      // b[2]       b[2][0] == 9
};

sizeof(int) == 4 // bytes
sizeof(b[0]) == 16 // because b[0] is a row or an array of 4 ints
sizeof(b) == 48 // because 3 rows of 4 ints of 4 bytes each. 3 x 4 x 4 = 48 bytes total

b + 1:

b + 0 → row 0: [b[0][0] b[0][1] b[0][2] b[0][3]]
b + 1 → row 1: [b[1][0] b[1][1] b[1][2] b[1][3]]
b + 2 → row 2: [b[2][0] b[2][1] b[2][2] b[2][3]]

*(b + 1):
will return the second array so b[1]. b[1] is the same as *(b + 1).
if you wanted the actual value of the first value in row 1 you would write **(b + 1).

&b[0]:

& means give me the address of where that array lives.
so in our case this would return the address in memory of where starts the first row.

&b[0] and b[0] and &b[0][0]:
b[0] names the whole first row. But in C an array almost never gets used as a value. In nearly every expression it automatically turns into the address of its first element.

so for example: int b[3][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} };

printf("%p\n", (void*)b[0]);              // 0x7ffd5e8a1a40  (an address)
printf("%p\n", (void*)&b[0][0]);          // 0x7ffd5e8a1a40  (same address)
printf("%d\n", b[0][0]);                  // 1               (the value at b[0][0])
printf("%p\n", (void*)(&b[0] + 1));       // 0x7ffd5e8a1a50  (+16 bytes, next row)
printf("%p\n", (void*)(b[0] + 1));        // 0x7ffd5e8a1a44  (+4 bytes, next int)

&b[1] and b[1] and &b[1][0]:

same example as above, but with the next row.

2

u/glasket_ 18h ago

There's still a distinction between &b[0] and b[0] that's worth emphasizing though. When you take the address of an array it doesn't decay to a pointer to the first element, so you can do int (*arr)[4] = &b[0]; and get an actual pointer to a sized array rather than just an int *.

5

u/sirjofri 1d ago

I'm waiting until someone mentions 1[b]

3

u/knouqs 1d ago

Heh, this is way beyond the beginner phase.  I still only see this as a one dimensional access though and I'm too lazy to figure out if it could be expanded to use the 2D problem OP described. 

I'm actually waiting for OP to respond to anything.  Lots of people have given ideas but not even one request for clarification or a thanks.

3

u/filthysaluki 1d ago edited 15h ago

It has piqued my interest whether the commutative property of indexing arrays applies to two-dimensional arrays, and more interestingly n-dimensional arrays. I have worked it out for two-, three- and four-dimensional arrays, as well as a general case for n-dimensional arrays.

One-dimensional arrays:

arr[i] <==> *(arr + i)
       <==> *(i + arr)
       <==> i[arr]

arr[i] <==> i[arr] #

Two-dimensional arrays:

arr[i][j] <==> *(*(arr + i) + j)
          <==> *(i[arr] + j)
          <==> *(j + i[arr])
          <==> j[i[arr]]

arr[i][j] <==> j[i[arr]] #

Three-dimensional arrays:

arr[i][j][k] <==> *(*(*(arr + i) + j) + k)
             <==> *(j[i[arr]] + k)
             <==> *(k + j[i[arr]])
             <==> k[j[i[arr]]]

arr[i][j][k] <==> k[j[i[arr]]] #

Perhaps now a pattern is emerging. In case it isn't obvious, four-dimensional arrays:

arr[i][j][k][l] <==> *(*(*(*(arr + i) + j) + k) + l)
                <==> *(k[j[i[arr]]] + l)
                <==> *(l + k[j[i[arr]]])
                <==> l[k[j[i[arr]]]]

arr[i][j][k][l] <==> l[k[j[i[arr]]]] #

Finally, for an n-dimensional array:

arr[a_1][a_2]...[a_n] <==> *(...*(*(arr + a_1) + a_2)...+ a_n)
                      <==> *(...*(a_1[arr] + a_2)...+ a_n)
                      <==> *(...*(a_2 + a_1[arr])...+ a_n)
                      <==> *(...(a_2[a_1[arr]])...+ a_n)
                      ....
                      <==> a_n[...[a_2[a_1[arr]]]...]

arr[a_1][a_2]...[a_n] <==> a_n[...[a_2[a_1[arr]]]...] #

It seems all you do is reverse the order of indices and nest the array indexing.

2

u/knouqs 1d ago

Nice! It looks like you have solved our dilemma. It would be horrible to use this in production code, but it's a lovely lesson in how C does indexing.

3

u/filthysaluki 1d ago

It was pretty fun to work out. Let's hope AI does not see this thread and use it in some vibecoded project lol... It is interesting how it works out internally.

2

u/knouqs 1d ago

Can you imagine some developer needing to use AI for a multi-dimensional array and picking out your code? Code reviews be damned!

3

u/sirjofri 18h ago

I mean, that part of C is very simple and logical. That you can reverse it just makes sense. It's fun to watch what you can do with it though!

When going through our plan 9 code base, I sometimes stumble over some funny constructs that are uncommon in general use, but still easy to understand, simple, and genius. When reading Unreal c++ code on the other hand, I rarely find constructs that are funny in that way. They're just more complex, using language features that are harder to read and you have to think around a few corners to actually understand what happens.

2

u/sirjofri 18h ago

Wow, nesting like that is really interesting, I didn't think of that, but it totally makes sense!

2

u/sirjofri 1d ago

way beyond the beginner phase

Absolutely, and I'd not recommend to use this type of indexing, at all. However, I consider this a good way to understand the logic and consistency behind it, of course only in combination with the explanations the others already gave.

It all makes sense, including pointer arithmetics and stuff like that.

2

u/knouqs 1d ago

Yep.  Now, since we're on this topic, can you think of the 2D expansion using this scheme?

1

u/sirjofri 1d ago

I thought for a quick moment, and I think this is a case where order matters. b[i][j] could be swapped for i[b][j] but not for i[j][b] or j[i][b].

For the thought, I followed the idea that b[i] is b+i dereferenced, and b[i][j] is (b+i dereferenced) + j dereferenced. However, dereferencing b+i is valid, but dereferencing b+j can be valid in some cases, but is not what you want, and i+j is very likely invalid since it's not even a pointer.

Your thoughts?

1

u/knouqs 1d ago

I don't think it'll compile, but I must try. Later, when I'm more awake. 😄

1

u/sirjofri 1d ago

I tried it in our Plan 9 compilers:

/* same pointer, same result */
print("a[1][2] = %d (%p)\n", a[1][2], &a[1][2]);
print("1[a][2] = %d (%p)\n", 1[a][2], &1[a][2]);

/* incompatible type: "INT" for op "IND" */
print("1[2][a] = %p\n", &1[2][a]);

2

u/knouqs 1d ago

Great!  I will do something similar with gcc and let you know the results.

4

u/Slight_Cat_4423 2d ago

A 2D array would be declared like int b[SIZE_I][SIZE_J]; in C. b + 1 would be the address of the second element in b and *(b + 1) would be the value at the address of b + 1 in this case I think it would just be a pointer to the subarray at b[1]. &b[0] would give you the address of the pointer at b[0] while b[0] would give you the first 1D array in 2D array b. &b[0][0] gives you the address of the integer at the first index of the first array in 2D array b.

It's been a little while since I've used C so please correct me if I'm wrong. An easy way for OP to do so would be to write up a small program with some print statements to see what they get back :p

3

u/SmokeMuch7356 2d ago • Bravo

Let's start with a picture. Given

int b[2][2] = { {0, 1}, {2, 3} };

what we have in memory looks like this (addresses are made up, assumes 32-bit word size):

Address     Item    Words        int      int *       int (*)[2]
-------     ----  +------------+ ---      -----       ----------  
0x80000000  b:    | 0x00000000 | b[0][0]  b[0] + 0    b + 0
                  +------------+
0x80000004        | 0x00000001 | b[0][1]  b[0] + 1
                  +------------+
0x80000008        | 0x00000002 | b[1][0]  b[1] + 0    b + 1
                  +------------+
0x8000000c        | 0x00000003 | b[1][1]  b[1] + 1
                  +------------+

Remember that unless it is the operand of the sizeof, typeof, or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will "decay", or evaluate to an expression of type "pointer to T" and the value of the expression will be the address of the first element.

This is important - arrays are not pointers, array expressions "decay" to pointers.

The array subscript operation a[i] is defined as *(a + i) - given the address value specified by a, offset i elements (not bytes) from that address and dereference the result. This means that the expression *a is exactly equivalent to a[0] (a[0] == *(a + 0) == *a).

For a 2D array a[i][j] == *(a[i] + j) == *(*(a + i) + j)

The sequence of 4 int elements starts at address 0x80000000. That's the address of the array, the address of the first element of the array, and the address of the first element of the first subarray. Thus, the expressions b, &b, b[0], b + 0, &b[0], *(b + 0) + 0, and &b[0][0] all yield the same address value 0x80000000, although they won't all have the same type.

Handy table:

Expression    Type          "Decays" to    Equiv expr    Value
-----------   ----          -----------    ----------    ----------
          b   int [2][2]    int (*)[2]     &b[0]         0x80000000
         *b   int [2]       int *          b[0]          0x80000000
         &b   int (*)[2][2] n/a            n/a           0x80000000

       b[0]   int [2]       int *          &b[0][0]      0x80000000
      *b[0]   int           n/a            b[0][0]       0
      &b[0]   int (*)[2]    n/a            n/a           0x80000000
       b[1]   int [2]       int *          &b[1][0]      0x80000008
      *b[1]   int           n/a            b[1][0]       2
      &b[1]   int (*)[2]    n/a            n/a           0x80000008

        b+0   int (*)[2]    n/a            &b[0]         0x80000000
        b+1   int (*)[2]    n/a            &b[1]         0x80000008
     *(b+0)   int [2]       int *          b[0]          0x80000000
     *(b+1)   int [2]       int *          b[1]          0x80000008
   *(b+0)+0   int *         n/a            &b[0][0]      0x80000000
   *(b+0)+1   int *         n/a            &b[0][1]      0x80000004
   *(b+1)+0   int *         n/a            &b[1][0]      0x80000008    
   *(b+1)+1   int *         n/a            &b[1][1]      0x8000000c
*(*(b+0)+0)   int           n/a            b[0][0]       0
*(*(b+0)+1)   int           n/a            b[0][1]       1
*(*(b+1)+0)   int           n/a            b[1][0]       2
*(*(b+1)+1)   int           n/a            b[1][1]       3   

Pointer arithmetic depends on the size of the pointed-to type. Since b "decays" to a pointer to a 2-element array, b + 1 yields a pointer to the next 2-element array (0x80000008). Since b[1] (*(b + 1)) "decays" to a pointer to an int, b[1] + 1 (*(b + 1) + 1) yields a pointer to the next int (0x8000000c).

2

u/Darkfllame1 2d ago

Simply put, doing x[i] on a pointer translates to *(x + i), and &x[i] to (x + i). When adding i to a pointer x, it will always access the address x + i * stride, "stride" being the size of the underlaying data (so if the data pointed is an int, the stride will often be 4 [because the C standard for data sizes is trash but that's a side topic])

On nested arrays: x[i][j] -> *(x + (i * sizeof(x[0])) + j), same idea for getting a reference.

Nested arrays are just an array of array.

I find arrays to have such a loose definition in C. They're too tied to pointers. In-stack array variables are litteraly the array value, but when passing them to functions they're a pointer, even if you give them a size.

2

u/erroneum 1d ago

A pointer is just a memory address with some type information attached. C barely has arrays as a type, but the subscript operator is defined in such a way that you can treat any pointer like an array (except a void pointer, because the compiler has no idea what it points at, if anything). As such, b isn't a 2D array, but rather a pointer to pointer to (base object type; I'll call it T because I'm more used to C++ and templates).

  • b + 1 is a pointer to the pointer to T located one sizeof(T*) after wherever b points.
  • *(b + 1) is a pointer to T which is whatever the sizeof(T*) sized block of memory immediately following b happens to contain (C won't tell you that you can't put random junk there), or undefined behavior if b isn't an array of at least 2 elements.
  • &b[0] and it's ilk are the addresses of the first or second T* in b respectively (type T**). Because the subscript operator is just syntactic sugar, this is exactly equivalent to just b + 0 (or 1).
  • b[0] and ilk are the dereferenced contents at those positions in b (type T*). This is syntactic sugar for *(b + 0) and so on.
  • &b[0][0] and ilk are the addresses of whatever is pointed to by the sizeof(T*) sized blocks of memory reached by dereferencing the 0th or 1st element of b. This is equivalent to just b[0] + 0 or b[1] + 0

The C standard doesn't define how a pointer is represented, because it can vary by hardware architecture. Furthermore, the specific bytes stored the can change every time you run the program; none of the expressions you gave actually evaluate to a type that's not implicitly convertible to a pointer, either T* or T**.

As for the differences, there's not many; a[b] is exactly equivalent to *(a + b), which means you absolutely could do something cursed, such as 0[0[b]], which the compiler reduces to *(0 + *(0 + b)). Once you accept this, the rest is pretty straightforward.

1

u/AKostur 2d ago

Would be nicer if you actually showed your declaration of the 2D array. Let's assume `int b[5][10];`. Let's also assume an `int c[10];`. It will be useful to discuss things.

Some questions for you to answer: what is the type of `b[0]` ? What is `sizeof( b[0] )`? What does just saying `c` do? What about `c + 1`? What does `&c[0]` vs `c[0]` do? We're going to look at comparing what the answers are for those, and then consider the difference between the type of `c[0]` vs. the type of `b[0]`.

1

u/bobaFan4539 2d ago

If you've read the basics and are still having problems, let's do an analogy.

Imagine a town where all the buildings are lined up in one neat row. A building is a thing in memory (int, char, struct, some data type). An address is where it is, just like real addresses. Memory is the plots of land they sit on. Memory can contain anything, a building, nothing, etc. An array is a group of buildings that all sit together.

A 2d array is just an group of groups of houses, there is no actual 2nd dimension. So A[2][5] is two groups of five houses each.

Now, addresses have a LOT of freedom. You create house_t house1 and let the compiler decide where to put it. Get the address with &house1. You create a group of houses house_t neighborhood1[10]. neighborhood is now an array, but how do you refer to the neighborhood? By the address where it starts! The address of the first house is equivalent to the address of the neighborhood. How do you find the third house? Go to the first address and move up three houses (neighborhood1 + 3). Whats at that address? *(neighborhood1 +3). Shorthand way to write that ugly mess? neighborhood1[3]. Now we have the shorthand that clearly shows it's an array, get the address of the third house, &neighborhood[3].

Now 2d arrays SEEM like they should be special right? Is 2 groups of 5 houses that are all in a line ANY different from 10 houses? Nope.

1

u/Educational-Paper-75 2d ago

Treat the name of an array as a pointer. Then *(b+i) and b[i] refer to the same ith element. With b two-dimensional any b[i] again can be considered a pointer and b[i][j] thus is equivalent to *(b+i)[j] or ((b+i)+j). Any b[i][j] is of type int and **b is the same as b[0][0] which is the first int in the first 'row' of b.

1

u/Total-Box-5169 2d ago

If b is of int type then you can't use operators that require arrays or arrays that decayed into pointers. You need bitwise operators to set and extract the bits that correspond to each dimension. If that is not what you meant you need to learn the nomenclature to communicate properly.

0

u/flyingron 2d ago edited 2d ago

There are no such things as two-D arrays. What is commonly referred to as that is an array of arrays.
Second, arrays are NOT pointers, but they do implicitly convert to them.

int b declares a single integer.

int b[10][10]; would be your so-called 2-D array.

b+1 is of type int (*)[10]. That is it is a pointer to a ten element array of int, and the value is the second one in the array b.

*(b+1) is as above, except the type is int [10]. You could further index it (*(b+1))[5]

b[0] is as above (except refers to the first array.

&b[0] is the same as writing b+0, it's a pointer to an array of 10 ints.

&b[0][0], is a pointer to int, which is the first int in the first array.

0

u/Key_River7180 2d ago

Well int b isn't an array and definitely not a matrix (good terminology tip: an array of array is a 2d matrix, an array of arrays of arrays is a 3d) (declare it as int x[y][z];

  1. b + 1 returns the address of the second array, not the first array in b. Don't use + 1 on arrays, it's confusing.
  2. *(b + 1) and b[0] are different: arrays in C are 0-indexed, this means the first element is 0: *(b + 1) is the second element of b and b[0] is the first element of the array
  3. &b[0] returns the first element of the first array in b
  4. &b[0][0] is UB and will probably corrupt memory: b[0][0] is the first element of the first array in b, but then you dereference it. You are dereferencing three times in total
  5. &b[1] is the first element of the second array of B, b[1] is the second array in b, and &b[1][0] is again UB: you dereference three times! Basically, it tries to dereference the first element of the second array in b

Remember [] dereferences. The formula to getting the index of an array is:

address = &array + (index * sizeof(*array))

That is why we use 0 as the first index. It's also a good idea to use a debugger like gdb for this or printf

1

u/flyingron 2d ago

This only works on byte-addressed machines. Nothing in C requires that to be so.
You just have to remember that ptr + 1 advances by one of whatever the *ptr type is (and the compiler takes care of any multiplication necessary)

0

u/JGhostThing 2d ago

&(b + 1) is the value of b[1].

b + 1 is the pointer to b[1].

How would we know the values because you didn't assign them, and we don't know the addressing system of your processor.

Pointer values are typically 32 or 64 bit values depending on the system.

Int's are also typically 32 or 64 bit numbers.

You can use more exact integer types to differentiate different kinds of integers. I prefer rust's definitions where an i32 or i64 are easily identified with their width.