简体   繁体   中英

How can I subtract from elements in an array with pointer notation?

I have a prompt asking me to declare and initialize an array of 4 doubles and to create a pointer to the array. Then I should add 30.0 to the second physical element of the array through the pointer via array notation. After, I should subtract 10.0 from the last array element through the pointer using pointer notation. Then I should reassign the pointer to the last element of the array.

I have tried figuring out how to subtract with pointer notation but no dice. I'm not following what needs to be done.

Here's my code so far:

int main () {
    double arr[4] = {10.0, 15.0, 20.0, 25.0};
    double *p = &arr;
    p[1] = 30.0; //array notation
    //code should go here for the subtracting ten part

    //code should go here assigning pointer to last element of array.
    //My idea of how this would look:
    p = (p + 3); // or 15.0
    //or:
    p = arr[3];
}

I tried doing something like (p+3) -=10.0 but I have a feeling that's wrong.

What I think the outcome should be: my arr elements being {10.0, 30.0, 20.0, 15.0} and p pointing to last element of array.

So array notation is really syntactic sugar over pointer arithmetic. In your code:

p[1] = 30.0;

Can also be written as

*(p + 1) = 30.0;

Similarly, if you want to "subtract 10.0 from the last array element through the pointer using pointer notation"

You would do this:

double *p = arr
*(p + 3) -= 10.0

Explanation:

When you are declaring an array you are declaring a series of values stored in contiguous memory (that means memory blocks next to each other). The reason you are able to access different elements in that array is that you know

  • Where the array starts
  • How far along you want to move

So really, array notation arr[2] (where arr is an array of double s) means "Go to the memory address of array arr , move along 2 * sizeof(double) , then give us the value stored there. Funnilly enough, that's exactly what *(p + 2) means, only it's broken down - the bit inside the brackets means "move along 2", and the star (the "dereference operator") means give us the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM