Home > OS >  C convert a 1D array into a 2D array
C convert a 1D array into a 2D array

Time:10-02

I am trying to convert a 1D array (81 characters null) and put it into a 9 by 9 grid of characters.

void convertArray(char lineHolder[])
{
    lineHolder[];      //I want this data
    converted2d[9][9];  //to go into that data
}
int drag(){
    char lineHolder[82];
    int puzzle = SOLVABLE;
    int last, i;
    last = i = 0;

    while ((last = getchar()) != EOF)
    {
      putchar(last);
        lineHolder[i] = last;
        i  ;
    }
    return 0;
}

CodePudding user response:

You can simply use memcpy().

char name[82] = ... ;
char puzzle[9][9];
memcpy(puzzle, name, sizeof puzzle);

The layout of both types is perfectly defined by the standard.


Alternatively, you can do it without copying by risking triggering Undefined behavior. Just cast name to char(*)[9] (a pointer to the row of 9 chars). Using this pointer will violate strict aliasing rule thus the outcome is not defined by C standard. However, it will likely work:

char (*puzzle)[9] = (char(*)[9])name;
// use puzzle[y][x] syntax later on

CodePudding user response:

Use union:

union myunion
{
     char name[81];
     char puzzle[9][9];
};

or pointer to array.

     char name[81];
     char (*puzzle)[9] = name;
  • Related