Search code examples
cpointerscastingcharstrcmp

How do I cast from char** to char* in C?


I have this problem: I have a matrix in which stores diferent characters. Now I have to compare these characters to another one, but when compiling, it says strcmp recives char* and I have char**. So, how do I cast it? This is the code I have:

For the matrix:

for (i = 0; i < x; i++){
        for (j = 0; j < y; j++){
            if (!fscanf(fol, "%c", &mat[i][j])){
                break;}
            //printf("%c", mat[i][j]);
            }
        }

The part I have problems with:

    for (x = 0; x < largo; x++){
        for (y = 0; y < ancho; y++){
            char *charcha;
            strcpy (charcha, mat[x][y]);

            //char *charcha = "%c", mat[x][y];
            int algo = strcmp(charcha, "0");
            if (algo == 0){
                printf (" ");
                }
            else{
            printf("%c", mat[x][y]);}
            }
            }

    printf ("\n");  

I tried with strcpy, but it failed as well :C

Thanks


Solution

  • If you want to compare strings, use:

    for (x = 0; x < largo; x++)
    {
       if ( strcmp(mat[x], "0") == 0 )
       {
          // Do whatever.
       }
       else
       {
          // Do whatever.
       }
    }
    

    If you want to compare characters, use:

    for (x = 0; x < largo; x++)
    {
       for (y = 0; y < ancho; y++)
       {
          if (mat[x][y] == '0' )
          {
             // Do whatever.
          }
          else
          {
             // Do whatever.
          }
       }
    }