Isac's answer is correct. I decided to only give an option that gives greater speed efficiency by paying the price to further fragment the memory. If it is a better option it is debatable and would need to analyze each case and test very well. I just wanted to give you a choice. This form is usually more idiomatic for C.
#include <stdlib.h>
#include <stdio.h>
int main() {
char str[] = "Ola. Tudo bem?\n Sim e contigo?\n Comigo esta tudo bem! Que tens feito?\n Trabalho no projeto!\n";
char **matriz = malloc(sizeof(char *) * 255);
int linha = 0;
matriz[linha] = malloc(255);
for (int caractere = 0, coluna = 0; str[caractere] != '#include <stdlib.h>
#include <stdio.h>
int main() {
char str[] = "Ola. Tudo bem?\n Sim e contigo?\n Comigo esta tudo bem! Que tens feito?\n Trabalho no projeto!\n";
char **matriz = malloc(sizeof(char *) * 255);
int linha = 0;
matriz[linha] = malloc(255);
for (int caractere = 0, coluna = 0; str[caractere] != '%pre%'; caractere++, coluna++) {
if (str[caractere] == '\n' || str[caractere] == '%pre%') {
matriz[linha][coluna] = '%pre%';
matriz[linha] = realloc(matriz[linha], coluna + 1);
matriz[++linha] = malloc(255);
coluna = -1;
} else {
matriz[linha][coluna] = str[caractere];
}
}
matriz = realloc(matriz, sizeof(char *) * linha);
for (int i = 0; i < linha; i++) {
printf("%s\n", matriz[i]);
}
}
'; caractere++, coluna++) {
if (str[caractere] == '\n' || str[caractere] == '%pre%') {
matriz[linha][coluna] = '%pre%';
matriz[linha] = realloc(matriz[linha], coluna + 1);
matriz[++linha] = malloc(255);
coluna = -1;
} else {
matriz[linha][coluna] = str[caractere];
}
}
matriz = realloc(matriz, sizeof(char *) * linha);
for (int i = 0; i < linha; i++) {
printf("%s\n", matriz[i]);
}
}
See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .
I based the same Isac algorithm, but I deleted the need to go through it 3 times.
Because there is too much memory, you need to cut what you do not use. There is a limitation that can only have 255 phrases with 254 characters each. Nothing has been verified if this is popping up, but the original algorithm also does not check whether malloc()
fails or even other problems that may occur.
You can also go relocating as per the character character requirement, but this will probably slow down. You can do hybrid algorithms.