Home > database >  i made custom strsplit function but output is weird
i made custom strsplit function but output is weird

Time:10-29

#include <iostream>

using namespace std;

int ft_strlen(char *str, char ascii[])
{
    int i = 0;
    while (!ascii[(short)str[i]] && str[i])
          i;
    return (i);
}

int word_count(char *s, char *ascii) {
    int i = 0, cnt = 0;
    while (s[i])
    {
        if (ascii[(short)s[i]])
            while (ascii[(short)s[i]])
                  i;
        else {
              cnt;
            while (!ascii[(short)s[i]] && s[i])
                  i;
        }
    }
    return (cnt);
}

char **ft_strsplit(char *s, char *ascii) {
    if (!s)
        return NULL;
    int wc = word_count(s, ascii);
    char **ans = (char **)malloc(wc);
    char *result;
    int i = 0, j = 0, k;
    while (wc--) {
        result = (char *) malloc(ft_strlen(s   i, ascii)   1);
        for (k = 0; s[i] != '\0';   i,   k) {
            if (!ascii[(short)s[i]])
                result[k] = s[i];
            else {
                result[i] = '\0';
                ans[j  ] = result;
                //inside the printf
                printf("%d %s\n", j - 1, ans[j - 1]);
                while (ascii[(short)s[i]])
                      i;
                break;
            }
        }
        result[i] = 0;
        ans[j] = result;
    }
    for (int i = 0; i < 5;   i) {
        printf("%d %s\n", i, ans[i]);
    }
    return ans;
}

int main()
{
    char ascii[256] = {0,};
    char d[] = ", ";
    int i = -1;
    while (d[  i])
        ascii[(short)d[i]] = 1;
    char str[90] = "it, is my, day 2,";
    char** ptr = ft_strsplit(str, ascii);
    for (int i = 0; i < 5;   i) {
        printf("%d %s\n", i, ptr[i]);
    }
    return 0;
}

I splited string and printing them, inside the printf printed well (plz look at the comment) but another printf's first string output weird.. I don't know why this happening. below is this code's output.

0 it
1 is
2 my
3 day
4 2
0 8P
1 is
2 my
3 day
4 2
0 8P
1 is
2 my
3 day
4 2

I expect all printf output like

0 it
1 is
2 my
3 day
4 2

I tried this code at https://cpp.sh/ this site. if this output depends on compiler plz tell me.

CodePudding user response:

It's been a ghastly number of years since I've done C code, but from what I recall, this line:

char **ans = (char **)malloc(wc);

will only give you one byte for each word in the string, when you actually need a pointer's length. I believe what you actually want there is:

char **ans = (char **)calloc(wc, sizeof(char*));

Also, why are you bothering learning C?? Even if you ignore the object-oriented features of it, C is a much "Better C" (that's one of it's design goals), and give you things like bool.

  • Related