0

hi i have been trying to convert a string map to an 2d array but the more i change the more i get confused. now it does not compile and complains its = NUL (edited i added malloc and seems that and gives segmentation fault).

#include <unistd.h>
#include <stdlib.h>


char    **stoa(char *str)
{
    int i;
    int j;
    int k;
    char **map;
    
    //int len = ft_strlen_line(str);
    //int row = ft_strlen(str);
    
    
    i = 0;
    j = 0;
    k = 0;
    
    //arow = row/len;
    //map = malloc(j * k sizeof(char*));
    
    map = malloc(j * sizeof(k));
    while(str[i])
    {
         if (str[i] == '\n')
        {
            k = 0;
            j++;
        }
    map[j][k] = str[i]; 
     k++;
     i++;
    }
    free(map);
    return (map);
    if (!(map = malloc(j * k * sizeof(char))))
    
    return NULL;
}



int main(void)
{
    
    char row12[] = "ABABABABAB\nABABABABAB\nABABABABAB\n\0";
    char **map;
    map = stoa(row12);

   
    return (0);
}
Camila
  • 1
  • 1

1 Answers1

0

Not tested.

char **stoa(char *str)

    size_t nlines = 0;
    size_t pos = 0;
    char **array = NULL;
    char **tmp;

    while(*str)
    {
        while(*str && str[pos++] != '\n');
        nlines++;
        tmp = realloc(array, (nlines + 1) * sizeof(*array));
        if(tmp) array = tmp;
        else break;
        array[nlines] = NULL;
        if(array[nlines - 1] = malloc(pos + 2));
        if(array[nlines - 1])
        {
            memcpy(array[nlines - 1], str, pos);
            array[nlines - 1][pos] = 0;
            str = str + pos;
            if(str == '\n') str++;
            pos = 0;
        }
        else break;
    }
    return array;
}
0___________
  • 60,014
  • 4
  • 34
  • 74