0

If I have a an array of ints, how could I directly edit each int?

int i = arr + 1; // Getting the integer in pos 1

i is just a copy, correct? If I set i = 4, then arr + 1 would still be 1.

Would this work?

int *i = &(arr + 1);
*i = 4;
0

4 Answers 4

3

You should use the array operators:

int i = arr[1];
arr[1] = 4;
Sign up to request clarification or add additional context in comments.

Comments

1

Change your code to this:

int *i = arr + 1;
*i = 4;

and it will work. Arrays in C are just pointers to first element in the array. So this arr + 0 will give address of first element in array and this arr + 1 is an address of second element.

Comments

1

You've got:

int arr[4] = {0, 1, 2, 3};

Want to edit it further?

arr[0] = 42;

// arr[] = {42, 1, 2, 3};

Want to change all of them at once? There's:

for(int i = 0; i < 4; ++i)
    arr[i] = i * 2;

// arr[] = {0, 2, 4, 6};

And don't forget memset()!

memset(arr, 42, 4);

// arr[] = {42, 42, 42, 42};

Want to change everything but the first element to 7?

memset(&arr[1], 7, 4 - 1);

// arr[] = {42, 7, 7, 7};


Would you like to know somethin' about pointers? (Here's a more useful link.)

See this? (If you can't, please stop reading this. Thanks!)

int *ptr = &arr[1];

It's equivalent to:

int *ptr = arr + 1;

Which is also equivalent to:

int *ptr = arr;
ptr = ptr + 1;

OK, now that we've got that down, let's show you a more efficient for-loop than the one I did above:

int *ptr = arr;
for(int i = 0; i < 4; ++i)
{
    *ptr = i << 2;
    // i * 2 == i << 2

    ++ptr;
}

// arr[] = {0, 2, 4, 6};

Not that you should code like that; the compiler will handle it for you, most likely.


Would you like another answer in the form of a series of questions?

Comments

0

Array indexing operators can do what you need.

arr[3] = 101; //assignment to array
int x = arr[37]; //get value from array

etc.

No need for for that memory arithmetic here..

2 Comments

I think you meant to say 'address arithmetic' instead of 'memory arithmetic'
yes thatd be better way to say it. or maybe pointer arithmetic

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.