0

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;
}

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

Use union:

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

or pointer to array.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.