0

How do I make an element of an array have the same dynamic value as another element? I need to translate something like:

value of array[2] = value pointed by array[4]

into code.

3
  • do you just copy the value of one element to another element? Commented Dec 11, 2011 at 21:49
  • So, in other words, you want the value pointed to by array[2] to always be the same as the value pointed to by array[4], without having to update array[2] manually? Commented Dec 11, 2011 at 21:49
  • Not sure I understand your question. If I set array[4] to 1, you want array[2] to be set to 1 also without using a second assignment statement or function call? If so, that's just not possible. Commented Dec 11, 2011 at 21:57

1 Answer 1

5

The only way I see to do it, is to use an array of pointers. Thus, changes to one position will affect a different position if both positions point to the same object.

Like so:

int* array[5];
array[2] = array[4] = malloc(sizeof(int));
*array[2] = 25;
// now, *array[4] will also be 25
Sign up to request clarification or add additional context in comments.

4 Comments

how do I translate it to code? I have char * array; and array[2] = array[4] does not work.
There's no need for the parentheses, [] has higher precedence than *.
Or if you want to have a little more fun, combine the last two lines: *(array[2] = array[4] = malloc(sizeof(int))) = 25 :)
@DavidGrayson: Sure, but it obfuscates the matter here. While the second line is part of the construction of array, the third shows how the indirection works.

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.