Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a variable in different function using pointer

I have got some C code and I am not allowed to change the structure. I have got an array called arr in my main function:

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

I have to change the values of this array in another function. Which is called inside the main function using:

change_array(arr);

The change_array method is implemented in another .c file. I am only allowed to make changes inside the change_array function.

void change_array(void *the_array)
{

}

In this function I want to change the values from arr. I found out that i can get the first value of the array using:

int first_value = *(int*)the_array;

And I can get the location of the first value using:

int location = the_array;

I tried to change the values with:

*the_array = 1;

but that did not solve my problem. Any ideas?

like image 724
JoeLiBuDa Avatar asked Feb 22 '26 14:02

JoeLiBuDa


1 Answers

You can create an int pointer in your change_array() function and modify the values through that as seen below. This works because the pointer you are passed is just the memory address of the first element in the array. So by assigning another pointer - of the appropriate type - to that same location, you can modify the original values directly. That is, any change you make to that memory location in your function will also change the original array because they occupy the same place in memory.

As pointed out by others, you will have no way of knowing the size of the array that they are passing you. You mentioned not being able to change the calling code, so I assume that won't be an option for you. Assuming your function will only be called with a fixed size is fragile, but it should still work for you.

#include "stdio.h"

void change_array( void * the_array );

int main()
{
int arr[ 4 ] = { 1, 2, 3, 4 };

printf( "Before:\n%d | %d | %d | %d\n", arr[ 0 ], arr[ 1 ], arr[ 2 ], arr[ 3 ] );
change_array( arr );
printf( "After:\n%d | %d | %d | %d\n", arr[ 0 ], arr[ 1 ], arr[ 2 ], arr[ 3 ] );

return( 0 );
}

void change_array( void * the_array )
{
int * arr_ptr = the_array; //NOTE: This is implicitly converting the void * to an int *
printf( "In the changing function:\n%d | %d | %d | %d\n", arr_ptr[ 0 ], arr_ptr[ 1 ], arr_ptr[ 2 ], arr_ptr[ 3 ] );
arr_ptr[ 0 ]  = 5;
arr_ptr[ 1 ]  = 6;
arr_ptr[ 2 ]  = 7;
arr_ptr[ 3 ]  = 8;
}  

You can see it in action here: http://codepad.org/6PXBeZlY


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!