0

I have a function that takes a pointer to an array of structs

typedef struct {
    bool isUsed;
    int count;
} MyStructure;

void Process(MyStructure *timeStamps, int arrayLength){
    for (int i = 0; i < arrayLength; i++){
        MyStructure *myStructure = &(*(timeStamps + i));
        if (myStructure->isUsed == true){
          /*do something*/
        }
    }

}

The way that I am accessing the array seems to be a little off.

&(*(timeStamps + i))

Is there a better way to do this?

5 Answers 5

6
&(*(timeStamps + i))

is equivalent with

&timeStamps[i]

which is, in turn, simply

timeStamps + i

That's all :)

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

Comments

2

The argument timeStamps is of type MyStructure*, which means that this line:

MyStructure *myStructure = &(*(timeStamps + i));

is equivalent to:

MyStructure *myStructure = timeStamps + i;

which is also equivalent to:

MyStructure *myStructure = &timeStamps[i];

Note that in this expression: &(*(timeStamps + i)), the timeStamps + i is a pointer to the element at index i (i.e. the address of this element), which is then dereferenced by using dereference operator (*) that returns an l-value of type MyStructure and then you retrieve the address of this element by using the address-of operator (&) which is equal to the address that timeStamps + i held at the beginning.

Comments

0
MyStructure *myStructure = &timeStamps[i];

Comments

0

Been a while since I worked in C, but as far as I remember the square brackets indexing operator ([]) is the same as adding to the pointer. So:

timeStamps[i] should be equivalent to *(timeStamps + i)

Therefore you should be able to use

myStructure = &timeStamps[i]

Comments

0

I would suggest:

void Process(MyStructure *timeStamps, int arrayLength){
    for (MyStructure *i = timeStamps; i < timeStamps + arrayLength; i++) {
        if (i->isUsed == true) {

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.