C - Copy a char into a char*

167 views Asked by At

I got some troubles while I'm trying to set a char into a char* ("string")

I got lines, which is all the txt lines I fetched before, and now I'm trying to assign a char to my char*, to filter it.

Here is my actual code :

void TreatDatas(char** lignes, int sizeLignes){ // all the lines, and the size of it.
    char** finalArray;
    finalArray = malloc(2048 * sizeof(char*));
    int sizeOfFinalArray = 0;

    int i;
    int j;

    char* s;
    char* savedCurrentString = "";
    int sizeOfCurrentString = 0;

    for (i = 0; i< sizeLignes; i++){
        s = lignes[i];
        for (j = 0; j < strlen(s); j++){ // I don't pass the first condition the first loop
            if (s[j] == ',' || s[j] == '.' || s[j] == ' ' || s[j] == '\n' || s[j] == ';' || s[j] == ':'){ // Separators list
                finalArray[sizeOfFinalArray] =  malloc(strlen(savedCurrentString) + 1);
                strcpy(finalArray[sizeOfFinalArray], savedCurrentString);
                savedCurrentString = "";
                sizeOfCurrentString = 0;
            }else{

                printf("%c , %s \n", s[j], savedCurrentString); // L - ""
                printf("%d", sizeOfCurrentString); // 0
                strncpy(savedCurrentString, s[j], 1); // error here

            }
        }
    }
    free(finalArray);
}
1

There are 1 answers

1
Izio On

Ok I change a bit the code, now it's better, but seems to duplicate some elements. And I don't know why. Excuse me, I'm a C beginer, but I'm curious and trying to understand how that works.

void TreatDatas(char** lignes, int sizeLignes){

    char** finalArray;
    finalArray = malloc(2048 * sizeof(char*));
    int sizeOfFinalArray = 0;

    int i;
    int j;

    char* s;
    char* savedCurrentString = "";
    int sizeOfCurrentString = 0;

    for (i = 0; i< sizeLignes; i++){
        s = lignes[i];
        printf("line : %d \n %s \n", i, s);
        StringSpliter(s);
//        for (j = 0; j < strlen(s); j++){
//            finalArray[sizeOfFinalArray] =  malloc(strlen(savedCurrentString) + 1);
//        }
    }
    free(finalArray);
}

char * StringSpliter(char* input){
    char separators[5][2] = {" ", ",", ";", ":", "."};

    char ** buffer;
    int bufferSize = 0;

    int i;

    for (i = 0; i < 5; i++){

        char* token = strtok(input, separators[i]);
        printf("%s", token);

        while( token != NULL )
        {
            printf( " %s\n", token );

            token = strtok(NULL, separators[i]);
        }

    }

    printf("\n");

    return "OSEF";
}

My output