Are structures copied when assigned?

Hello coders, I’m Java coder, but my Java solution for Remember the recipe problem is getting TLE, so I’m trying to convert my solution to C/C++ and I’m facing following problem:

I have this structure (changed, it’s not related to problem):

struct Person {
	int w; // height
	int h; // weight
};

I have global variable (array):

Person persons[10];

also helper function for debug:

void personPrint( int i ) {
	printf( "w=%d, h=%d\n", persons[i].w, persons[i].h );
}

and now the main function where the problem appear:

int main() {
	memset( persons, 0, sizeof(persons) ); // init
	
	Person p = persons[0]; // copied ?
	p.w = 75;
	p.h = 175;
	
	personPrint( 0 );
}

it prints w=0, h=0.

In Java this works as expected

static class Person {
    int w;
    int h;
}

private static Person[] persons = new Person[ 10 ];
static {
    for ( int i = 0; i < persons.length; i++ )
        persons[i] = new Person();
}

static void personPrint( final int i ) {
    System.out.println( String.format( "w=%d, h=%d\n", persons[i].w, persons[i].h ) );
}

public static void main( final String[] args ) {
    final Person person = persons[0];

    person.w = 75;
    person.h = 175;

    personPrint( 0 );
}

I’m used to use local variables to simplify things, that’s the reason why I want to use local variable p.

Additional question (similar to this one) is: How to do same this with multidimensional arrays?

In Java this works fine:

int[][] d2 = new int[10][20];
int[] d1 = d2[0];

How to do similar thing in C/C++?

Thanks.

Yes they are, according to this question on StackOverflow.

I was mislead with Java behaviour, but later I realized it is the same with integers

int a[] = { 1, 2, 3 };
int t = a[0];
t *= 10;
printf( "a[0]=%d, t=%d\n", a[0], t ); // here it's clear why a[0] is 1 still

if you want to use a variable that is “pointing” to structure, or integer arrays, you should use pointers.

int t = a[0];

means :

let’s declare an integer variable called t, AND, initialize its value to the same value as a[0].
but t is not a[0]. :slight_smile:

their values are equal, that’s all. if you modify t, a[0] won’t be, and the same the other way.

instead :

int* t = &a[0]; // (or int* t = a;)

Then any operation on *t (a[0]) will give you the expected result.

//