1

The problem is the following: Have to check if the words in the matrix are palindromes or not. Have to read the words as well. My main problem is introducing the words because until now I could only do a function reading the first letter, not the whole word. After that, I think that I can check alone if it is a palindrome or not. This is an example of data:

mat←["ac" "lup" ]
    ["ou" "lupul"]
    ["ABBA" "greu" ]
m←3 number of rows
n←2 number of columns

This what I wrote until now: A function where you introduce the words:


    char** read(int *m ,int *n)
{
    printf("No of lines=");
    scanf("%d",m);
    printf("No of columns=");
    scanf("%d",n);

    char **a=(char**)malloc(*m*sizeof(char*));

    for (int i=0;i<*m;i++)
    {
        a[i]=(char*)malloc(*n*sizeof(char));
        for (int j=0; j<*n; j++)
        {
            fflush(stdin);
            printf("Element [%d][%d]=",i,j);
            gets(a[i]+j); // <=>  &a[i][j]
        }
    }
    return a;
}

Another one which displays it:

void display(char **x, int m, int n)
{
    for (int i=0; i<m; i++)
    {
        for (int j=0; j<n; j++)
            printf("%c ",x[i][j]);
        printf("\n");
    }
}

Another one which deletes the data:

void freematrix(char **x, int m)
{
    for (int i=0; i<m; i++)
        free(x[i]);
    free(x);
}

This is the main part:

int main()
{
    int m, n;
    char **mat;
    mat=read(&m,&n);
    display(mat,m,n);
    freematrix(mat,m);
    return 0;
}
  • 1
    If I understand your problem, then a[i]=(char*)malloc(*n*sizeof(char)); is not correct, you are allocating n bytes when n is the number of columns in the table, not the length of the string that you want to store. You need to read the string first to know the size, then allocate the space in the table to store it. – john elemans Jan 21 '22 at 16:46
  • [Why `gets()` is too dangerous to be used — ever!](https://stackoverflow.com/q/1694036/15168) – Jonathan Leffler Jan 21 '22 at 16:47
  • 3
    You need to create a 2D array of pointers, each of which points to a string. Your return type probably needs to be `char ***` ([Beware of Three-Star Programmers](http://c2.com/cgi/wiki?ThreeStarProgrammer)), and you need to allocate space for an alternative to `gets()` to read into. Beware of [using `fflush(stdin)`](https://stackoverflow.com/q/2979209/15168)! What you've got supports a vector (1D matrix) of strings and not a 2D matrix. – Jonathan Leffler Jan 21 '22 at 16:53
  • Thank you for your help I would be very thankful if someone would help with an actual code not just advise. – Székely Réka Jan 25 '22 at 09:12

1 Answers1

1

Try this:

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

#define MAX_ROWS    8   // to limit the usecase
#define MAX_COLS    8
#define MAX_MAT_STR_LEN 15 //

char* str_dupe (const char* str, const int max_slen)
{
    if (!str || max_slen < 1) return NULL;
    char* dupe = malloc (max_slen + 1);
    if (!dupe) {
        perror("\nERROR: str_dupe-malloc");
        return NULL;
    }
    dupe[max_slen] = '\0'; // guard
    for (int ci =0; ci < max_slen; ++ci) {
        dupe[ci] = str[ci];
        if ('\0' == dupe[ci])
            break;  // stop copying
    }
    return dupe;
}


void free_strMatrix (char ***sm, const int rows, const int cols)
{
    if (!sm || rows < 1 || cols < 1) return;

    for (int ri = 0; ri < rows; ++ri) {
        if (sm[ri]) {
            for (int ci = 0; ci < cols; ++ci) {
                if (sm[ri][ci]) { // check if it's NULL
                    free (sm[ri][ci]);
                    sm[ri][ci] = NULL;  //prevent dangling pointers
                }
            }
            free (sm[ri]); // row of string pointers
            sm[ri] = NULL; // good practice
        }
    }
    free (sm);
}


char*** read_strMatrix (int *rows, int *cols)
{
    while (1) {
        printf ("\nChoose Rows [1..%d]: ", MAX_ROWS);
        if (1 == scanf("%d", rows) && *rows > 0 && *rows <= MAX_ROWS)
            break;
        else
            printf ("\nERROR: Invalid Row-Count. Try Again!");
    }
    while (1) {
        printf ("\nChoose Columns [1..%d]: ", MAX_COLS);
        if (1 == scanf("%d", cols) && *cols > 0 && *cols <= MAX_COLS)
            break;
        else
            printf ("\nERROR: Invalid Column-Count. Try Again!");
    }

    char*** sm = (char***) calloc ((*rows), sizeof (char**));
    if (NULL == sm) {
        perror("read_strMatrix-malloc-1");
        return NULL;
    }
    for (int ri = 0; ri < *rows; ++ri) {
        sm[ri] = (char**) calloc ((*cols), sizeof (char*));
        if (NULL == sm[ri]) {
            perror ("read_strMatrix-malloc-2");
            //ideally you should free allocated memory before return
            free_strMatrix(sm, *rows, *cols);
            return NULL;
        }
    }
    char str[256]; //interim string buffer;
    for (int ri = 0; ri < *rows; ++ri) {
        for (int ci=0; ci < *cols; ++ci ) {
            printf ("String for strMatrix[%d][%d] : ", ri, ci);
            // strings more than 255 chars will be split ; so be within limit duing input
            while (1 != scanf ("%255s", str));
            // only copying MAX_MAT_STR_LEN chars
            sm[ri][ci] = str_dupe (str, MAX_MAT_STR_LEN);
            if (NULL == sm[ri][ci]) {
                perror("read_strMatrix-strndup");
                //ideally you should free allocated memory before return
                free_strMatrix (sm, *rows, *cols);
                return NULL;
            }
        }
        printf ("\n");
    }
    return sm;
}


void disp_strMatrix (char ***sm, const int rows, const int cols)
{
    if (!sm || rows < 1 || cols < 1) return;
    printf ("\nStringMatrix [%d][%d]:\n", rows, cols);

    for (int ri = 0; ri < rows; ++ri) {
        if (sm[ri]) {
            for (int ci = 0; ci < cols; ++ci)
                printf ("%s\t", sm[ri][ci]);
        }
        printf ("\n");
    }
    printf ("\n");
}


int main()
{
    int rows, cols;
    char ***strMatrix;
    strMatrix = read_strMatrix (&rows, &cols);
    if (!strMatrix) {
        printf ("\nERROR: reading strMatrix\n");
        return 1;
    }
    disp_strMatrix (strMatrix, rows, cols);
    free_strMatrix (strMatrix, rows, cols);
    strMatrix = NULL; // good practice

    return 0;
}

You can also prepare an input.txt file like:

3 4
aaaaa   sssss   ffg gggg    
hhhh    jj  kkkkkk  lllll   
qqq wwwww   eeeee   rrrrr

On Linux you can run the program like:

./a.out < input.txt 
जलजनक
  • 3,072
  • 2
  • 24
  • 30