C PLIS HELP --> I want to create an array in a function and return it fully filled, but in my code it returns null

Asked

Viewed 55 times

-1

#include <stdio.h>


char * criar_matriz() {

  char *matriz[8][10] = {};
  matriz [7][3] = "*";
  matriz [7][4] = "*";  
  matriz [7][5] = "*";
  matriz [7][6] = "*";

  for(int i = 0; i<8; i++) {
    for(int j = 0; j<10; j++) {
        matriz[i][j] = " ";
}
  }
 for(int l = 1; l<3; l++) {
for(int c = 2; c<=6; c++) {
    matriz[l][c] = "#";
    printf("%s\n", matriz[l][c]);
    }
  }
   return matriz[8][10];
}

 void elegante (char *matriz[8][10]) {
  for(int i = 0; i<8; i++) {
    for(int j = 0; j<10; j++) {
      printf("%s", matriz[i][j]);
    }
    printf("\n");
  }
}



int main() {
  char *matriz[8][10]= {};
  matriz[8][10] = criar_matriz();
  elegante(matriz);

  return 0;
}
  • 1

    First you are sure you want to define an array of pointers to char or actually want to declare a char matrix? Second: study the scope of variables. The way you are doing the matrix is offset at the end of the execution.

1 answer

0

Try this way:

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

char** GetMatriz(const int L, const int C) {

    char** matriz;

    matriz = (char**) malloc ( L * sizeof(char*) );

    for(int i = 0; i < L; i++) {

        matriz[i] = (char*) malloc( C * sizeof(char) );

        for(int j = 0; j < C; j++) {

            matriz[i][j] = '*';

        }
    }

    return matriz;

}


int main() {

    char** matriz = GetMatriz(10, 10);

    for(int i = 0; i < 10; i++) {

        for(int j = 0; j < 8; j++) {

            printf("%c ", matriz[i][j]);

        }

        printf("\n");

    }


    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.