EDIT: I have fully fixed my code now. Here it is:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main(){
int n, i , j;
char **mensagem;
char leitura[1000];
FILE *arquivo;
arquivo = fopen("entrada.txt", "r");
fgets(leitura, 1000, arquivo);
fclose(arquivo);
arquivo = fopen("entrada.txt", "r");
n = sqrt(strlen(leitura));
mensagem = malloc(n * sizeof(char *));
for (i = 0; i < n; i++){
mensagem[i] = malloc(n * sizeof(char));
}
for (j = 0; j < n; j++){
for (i = 0; i < n; i++){
fscanf(arquivo, "%c", &mensagem[i][j]);
}
}
for (j = 0; j < n; j++){
for (i = 0; i < n; i++){
if(mensagem[j][i] == '*'){
printf(" ");
i = n - 1;
}
else {
printf("%c", mensagem[j][i]);
}
}
}
fclose(arquivo);
free(mensagem);
return 0;
}
The idea is to decypher messages like Cesar did back in the days :D. I read a coded message from a .txt file. I read the entire line then I dynamically allocate an array of arrays.
That way I can print the columns and the message will be printed normally.
Here’s my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main(){
int n, i , j;
char **mensagem;
char leitura[1000];
FILE *arquivo;
arquivo = fopen("entrada.txt", "r");
fgets(leitura, 1000, arquivo);
n = sqrt(strlen(leitura));
mensagem = (char **)malloc(n * n * sizeof(char));
for (j = 0; j < n; j++){
for (i = 0; i < n; i++){
fscanf(arquivo, "%c", &mensagem[i][j]);
}
}
for (j = 0; j < n; j++){
for (i = 0; i < n; i++){
if(mensagem[i][j] == '*'){
printf(" ");
i = n - 1;
}
else {
printf("%c", mensagem[i][j]);
}
}
}
fclose(arquivo);
free(mensagem);
return 0;
}
Here’s the data in the file:
AEEUMOLSHMSCGT*AGU2A***L:****T*****A
And here’s the expected output:
ALG2: ESTA EH UMA MSG OCULTA
And here’s the logic behind it:
A E E U M O L S H M S C G T * A G U 2 A * * * L : * * * * T * * * * * A
I do know that the problem is exactly with the call of printf, but I’m unsure on how to fix it.
This is a classic example of “two stars does not a two-dimensional array make”.
mensagem = (char **)malloc(n * n * sizeof(char));
mensagemis a pointer to a block ofn * nbytes. However, when you domensagem[i][j], the compiler will read the value of the pointer, addi, and then read the pointer at that address. What is that pointer set to? Whatever happens to be ati * sizeof(char *)into your allocated memory – probably zero.You need to do a two-stage allocation, first allocating
npointers, then allocating storage for each string ofnbytes.Edit: I intentionally haven’t written the code to solve your problem, because you will leard much more from writing it yourself…