Home > OS >  How to set a value in a multi-dimensional struct array using a struct pointer?
How to set a value in a multi-dimensional struct array using a struct pointer?

Time:10-06

I have a struct:

typedef struct{
int age;
int height
}Human;

I create a multi-dimensional array with that struct:

Human human_table[3][2]={ 
{{1,1},{1,1}},
{{1,1},{1,1}},
{{1,1},{1,1}},
};

I create a Pointer to the table

typedef struct human_table *humanPointer;

Now For the question, how can I create a function to modify the table above?

I currently have this:

void Modify_Human_age(humanPointer human_table, int x, int y, int New_Age)
{
human_table[x][y]->age=New_Age;
}

But I get an error and was looking for help on how to fix the Modify_Human_age function.

Thanks

CodePudding user response:

  1. Never ever hide pointers behind the typedefs. It makes code much harder to maintain and read. So delete that typedef from your code.

  2. Multidimensional tables in C are in the fact tables of tables. So the 2D table is a table of rows. So id the X is a row size and Y is number of rows the definition of the array should be type arr[Y][X]

  3. For indexes and sizes use the correct (size_t) type indestead of int

void Modify_Human_age(size_t x, size_t y, Human (*human_table)[x],  int New_Age)
{
    human_table[y][x].age=New_Age;
}
  • Related