Reputation: 153
I have a seemingly simple question regarding array pointer in C. I am trying to understand a portion of code written in C, so i can port it to C#. The data types and functions are defined as follows:
/* header file */
/* definition of data_t type */
typedef unsigned short uint16_t;
typedef uint16_t data_t;
/* the function the type data_t is used */
#define FOO(d) do {
d[0] = 1;
d[1] = 2;
} while (0)
/* source file */
/* the function where FOO is used */
static int BAR(data_t* const data)
{
FOO(data + 1);
}
When calling FOO(..) within BAR(..), what does "data + 1" mean? As i understand, data is an array from type data_t. I wasn't able to find an exact example on stackoverflow or else, therefore i am confused about the meaning of it. I have three options in my mind how an appropriate assignment in C# could look like:
The first option makes sense to me. But when taking a look into the function FOO(..), it makes no sense, because FOO is using "data" like an array.
Can anyone give me a hint?
Thanks,
Michael
Upvotes: 0
Views: 558
Reputation: 2731
In C pointers and arrays are usually interchangeable.
data_t*
is equivalent to data_t[]
in most cases, and the use of the array notation is used to simplify the dereferencing of the pointers for assignment.
data[0] = 1;
data[1] = 2;
can be replaced with
*(data) = 1;
*(data+1) = 2;
It really is just semantics, although the use of the macro is ugly. Either way you can access out of range memory locations and cause trouble when accessing memory which is unassigned.
*(data+1) != data + 1
data + 1
- Memory location at the pointer data + 1 * (size of data type of the pointer). In other words, it is one unit over from the position of data.
*(data + 1)
- Value at memory location of said data type.
Upvotes: 2
Reputation: 36463
In this context:
data + 1
Means:
data + sizeof(data_t);
Because data
is a pointer of type data_t
pointer arithmetic is applied so that + 1
results in sizeof(data_t)
bytes further than data
.
So your first assumption is correct.
Upvotes: 2