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.