C - создать добавочную матрицу - PullRequest
0 голосов
/ 26 сентября 2018

Я точно не знаю, является ли добавление правильным термином, но вот объясненная проблема:

Я хочу создать M, то есть, скажем, 5*5 матрицу строк, начинающуюся сэлемент (скажем, символ 5).Первая строка матрицы будет выглядеть следующим образом:

51 52 53 54 55

После этого я возьму содержимое M[1][1] и добавлю его в соответствующие столбцы, создав вторую строку:

 51  52  53  54  55
511 512 513 514 515

Затем взяв содержимое M[1][2] для создания третьей строки:

 51  52  53  54  55
511 512 513 514 515
521 522 523 524 525

В конце M будет выглядеть так:

 51  52  53  54  55
511 512 513 514 515
521 522 523 524 525
531 532 533 534 535
541 542 543 544 545

Если, скажем, матрица имеет вид 7*7, то седьмая строка возьмет содержимое M[2][1] и добавит его в соответствующие столбцы, как показано ниже:

5111 5112 5113 5114 5115

Пока мой код выглядит так:

#include <stdio.h>
#include <string.h>

#define RowMin 1
#define RowMax 7
#define ColMin 1
#define ColMax 7

/* here, I define a type called MATRIX, containing Mem (matrix of strings), 
   number of effective rows, and number of effective columns.
   My matrix will start from 1 and with 8 valid row and 8 valid column */
typedef struct { 
    char Mem[RowMax+1][ColMax+1];
    int NRowEff;
    int NColEff;
} MATRIX;

/* these are the selectors */
#define NRowEff(M) (M).NRowEff
#define NColEff(M) (M).NColEff
#define Elmt(M,i,j) (M).Mem[(i)][(j)]

void MakeMATRIX (int NR, int NC, MATRIX * M)
/* This is a procedure to create a matrix with predefined NR and NC */
{
    NRowEff(*M) = NR;
    NColEff(*M) = NC;
}

void CreateAppend (MATRIX *M, int NR, int NC, char elmt)
/* this is the procedure to create the matrix as defined in the problem */
{
    MakeMATRIX(NR,NC,M); /* first we make the matrix */
    /* these two are counters */
    int i = 1;
    int k = RowMin + 1; 

    /* to create the first row, I call this procedure */
    Append(M,i,&elmt);

    /* the next rows will be created with this loop */
    for (int i = RowMin; i <= NRowEff(*M); ++i)
    {
        for (int j = ColMin; j <= NColEff(*M); ++j)
        {
            /* first i take the element of the matrix that i want to append 
            */
            elmt = Elmt(*M,i,j);
            /* call the append procedure */
            Append(M,k,&elmt);
            /* add 1 to the counter */
            if (k <= NRowEff(*M))
                k++;
        }
    }
}

void WriteMATRIX (MATRIX M)
/* this is a procedure to write matrix to the screen */
/* e.g. writing 3 x 3 matrix will look like this
   1 2 3
   4 5 6
   8 9 10
*/
{
    for (int i = RowMin; i <= NRowEff(M); ++i)
    {
        for (int j = ColMin; j <= NColEff(M); ++j)
        {
            printf("%s", Elmt(M,i,j));
            if (j < NColEff(M))
                printf(" ");
        }
        if (i != NRowEff(M))
        {
            printf("\n");
        }
    }
}

void Append (MATRIX *M, int i, char * elmt)
/* this is the implementation of Append procedure that is called in 
   CreateAppend */
{
    char appendix[2];

    for (int j = ColMin; j <= NColEff(*M); ++j)
    {
        /* because I'm appending the respective column number to the elmt, I 
           will have to cast int to a const char* using sprintf */
        sprintf(appendix,"%d",j);
        /* then I append the elmt and the appendix using strcat */
        strcat(elmt, appendix);
        /* the new element of the matrix is elmt */
        Elmt(*M,i,j) = *elmt;
    }
}

В основной программе я пишу это:

int main(void)
{
    MATRIX MCPU;
    char elmt;

    elmt = '5';

    CreateAppend(&MCPU,5,5,elmt);
    WriteMATRIX(MCPU);
}

Когда я запускаю эту программу в режиме отладки, я получаю ошибку сегментации.Я действительно не знаю, где я могу испортить, и если кто-то может указать мне на это, это будет полезно!Также я предполагаю, что цикл работает неправильно, но я не замечаю ошибки.

...