that_one_nigga_you_k

lista 4 com função de ler, mostrar e apagar

Dec 15th, 2023 (edited)
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. void ler(char*** str, int* indice) {
  6.     //ponteiro triplo q aponta para a matriz
  7.  
  8.     int flag = 1;
  9.  
  10.     while (flag) {
  11.  
  12.         /*daqui até o fim da função a gente manipluna da mesma forma, a diferença é q são os ponteiros apontando para os indices da matriz*/
  13.         (*str)[*indice] = (char*)malloc(1000 * sizeof(char));
  14.  
  15.         if ((*str)[*indice] == NULL) {
  16.             printf("deu errado essa porra ae");
  17.             flag = 0;
  18.         }
  19.  
  20.         printf("digite a string: \n");
  21.  
  22.         if (fgets((*str)[*indice], 1000, stdin) != NULL) {
  23.             if ((*str)[*indice][0] == '\n') {
  24.                 flag = 0;
  25.             }
  26.            
  27.             else {
  28.                 (*str)[*indice][strcspn((*str)[*indice], "\n")] = '\0';
  29.                 (*indice)++;
  30.                 *str = realloc(*str, (*indice + 1) * sizeof(char*));
  31.  
  32.                 if (*str == NULL) {
  33.                     printf("\n deu ruim isso aí ein\n");
  34.                     flag = 0;
  35.                 }
  36.             }
  37.         }
  38.        
  39.         else {
  40.             flag = 0;
  41.         }
  42.     }
  43. }
  44.  
  45. void mostrar(char*** str, int* indice){
  46.     printf("\nas strings\n");
  47.     for(int i = 0; i < *indice ; i++){
  48.         printf("%s\n", (*str)[i]);
  49.     }
  50. }
  51.  
  52. void apagar(char*** str, int* indice){
  53.     for(int i = 0; i < *indice ; i++){
  54.         printf("apagando a strins '%s'\n", (*str)[i]);
  55.         free((*str)[i]);
  56.     }
  57.     printf("apagando o resquicio da matriz\n");
  58.     free((*str));
  59. }
  60.  
  61.  
  62. int main(){
  63.     char** str = NULL;
  64.  
  65.     str = (char**)malloc(1 * sizeof(char*)); //malocando a quantidade de strings
  66.  
  67.     if(str == NULL){
  68.         printf("\ndeu mto ruim saporra\n");
  69.     }
  70.  
  71.     int indice = 0;
  72.  
  73.     ler(&str, &indice);
  74.    
  75.     mostrar(&str, &indice);
  76.  
  77.     apagar(&str, &indice);
  78.  
  79.     printf("\n\naté mais...\n\n");
  80.  
  81.     return 0;
  82. }
Add Comment
Please, Sign In to add comment