4

Is there anyway I can move the pointer in the array. So, like you move where the pointer is pointing at in the array. For files, I know that you can use fseek with something like fread to only copy from a specific location.

I'm trying to copy parts of an array into different files. With fwrite, it doesn't give the option to start from a specific location, so I'll need to move the pointer to somewhere in the array, then copy a part of the array into a file.

1
  • You can use &array[index] to get a pointer to an element of the array. Commented Oct 6, 2020 at 1:11

1 Answer 1

4

sure you can move a pointer. Say we have an array of ints

int arr[50];

set p to point at the first element

int*p = &arr[0];

now move it along by 10

p += 10;

p now points at arr[10];

Addition on a pointer is defined as incrementing the pointer by n times the size of each elements. Subtraction works too. Be aware of going off either end though, C wont look out for you. Ie this

p += 500;

will compile but will lead to undefined behavior if you try to use p;

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

4 Comments

Ok, thanks. I didn't realize that you could use & to receive the pointer to an element of an array. That makes lots of sense.
@AlexZhao you can do int*p=&arr[10]
Yes, except that I can keep incrementing to keep pointing to different elements of the array. Ok, thanks.
@pm100 Actually, you can just write int*p = arr; instead of int*p = &arr[0];

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.