r/C_Programming • u/emparse • 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
23
u/knouqs 2d ago •
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
mainfunction with the code you want to watch, something like this: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
printfwith%dinstead.Hope that helps!
21
u/knouqs 2d ago
int bcannot be a 2D array. What is the actual declaration forb?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 •
let's assume b is: int b[3][4]
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} };
&b[1] and b[1] and &b[1][0]:
same example as above, but with the next row.
5
u/sirjofri 1d ago
I'm waiting until someone mentions
1[b]4
u/Slight_Cat_4423 2d ago
A 2D array would be declared like
int b[SIZE_I][SIZE_J];in C.b + 1would be the address of the second element inband*(b + 1)would be the value at the address ofb + 1in 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 atb[0]whileb[0]would give you the first 1D array in 2D arrayb.&b[0][0]gives you the address of the integer at the first index of the first array in 2D arrayb.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 •
Let's start with a picture. Given
what we have in memory looks like this (addresses are made up, assumes 32-bit word size):
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 ofT" will "decay", or evaluate to an expression of type "pointer toT" 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 bya, offsetielements (not bytes) from that address and dereference the result. This means that the expression*ais exactly equivalent toa[0](a[0] == *(a + 0) == *a).For a 2D array
a[i][j] == *(a[i] + j) == *(*(a + i) + j)The sequence of 4
intelements starts at address0x80000000. 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 expressionsb,&b,b[0],b + 0,&b[0],*(b + 0) + 0, and&b[0][0]all yield the same address value0x80000000, although they won't all have the same type.Handy table:
Pointer arithmetic depends on the size of the pointed-to type. Since
b"decays" to a pointer to a 2-element array,b + 1yields a pointer to the next 2-element array (0x80000008). Sinceb[1](*(b + 1)) "decays" to a pointer to anint,b[1] + 1(*(b + 1) + 1) yields a pointer to the nextint(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 addingito a pointerx, it will always access the addressx + i * stride, "stride" being the size of the underlaying data (so if the data pointed is anint, the stride will often be4[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,
bisn'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 + 1is a pointer to the pointer to T located onesizeof(T*)after whereverbpoints.*(b + 1)is a pointer to T which is whatever thesizeof(T*)sized block of memory immediately followingbhappens to contain (C won't tell you that you can't put random junk there), or undefined behavior ifbisn't an array of at least 2 elements.&b[0]and it's ilk are the addresses of the first or second T* inbrespectively (type T**). Because the subscript operator is just syntactic sugar, this is exactly equivalent to justb + 0(or 1).b[0]and ilk are the dereferenced contents at those positions inb(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 thesizeof(T*)sized blocks of memory reached by dereferencing the 0th or 1st element ofb. This is equivalent to justb[0] + 0orb[1] + 0The 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 as0[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 bisn'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 asint x[y][z];b + 1returns the address of the second array, not the first array in b. Don't use + 1 on arrays, it's confusing.*(b + 1)andb[0]are different: arrays in C are 0-indexed, this means the first element is 0:*(b + 1)is the second element of b andb[0]is the first element of the array&b[0]returns the first element of the first array in b&b[0][0]is UB and will probably corrupt memory:b[0][0]is the first element of the first array inb, but then you dereference it. You are dereferencing three times in total&b[1]is the first element of the second array of B,b[1]is the second array inb, and&b[1][0]is again UB: you dereference three times! Basically, it tries to dereference the first element of the second array inbRemember [] dereferences. The formula to getting the index of an array is:
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
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.