Reputation: 143
Right now I'm looking over some C code and they have some pointer syntax that I'm confused about. So first they declared a pointer like so:
int32_t *p_tx_buf=NULL;
Then later on they wrote:
p_tx_buf = malloc(...math... );
The stuff in the middle is just math to calculate the size of a file, I'm assuming it's not important. After that, they wrote:
p_tx_buf[0] = 0
I'm rather confused about the []
. How does that work with an integer pointer? I thought the []
was for indexing things, so I'm confused on how you can use this with a pointer.
Upvotes: 1
Views: 75
Reputation: 1431
the malloc command I assume was some multiplication of the sizeof(int32_t)
say:
p_tx_buf = malloc(2*sizeof(int32_t));
you now have allocated enough memory space for 2 int32_t variables you can access them by:
*(p_tx_buf) and *(p_tx_buf+1)
or
p_tx_buf[0] and p_tx_buf[1]
Upvotes: 1
Reputation: 859
Just to expound a bit on the answers already provided, the "math" you are referring to is probably not calculating the size of a single file, rather it is multiplying the size of a file times some integer.
The result is that enough space is allocated for several file structures. The pointer winds up pointing to the first of several file structures laid out sequentially in memory. The index [0]
means point to the first of those file structures (i.e., an offset of 0)
Upvotes: 1
Reputation: 6846
In C (and also C++), array[n]
is equivalent to *(array+n)
. They mean exactly the same thing and produce exactly the same result.
Upvotes: 4