Создание массива строк из пользовательского ввода

У меня есть следующая простая программа, которая будет принимать пользователя string введите (" ") из терминала и проанализируйте ввод в массив строк (называемый массив), символ за символом. Всякий раз, когда встречается числовой символ, создается новая строка: т.е. ./programname "Hello1 my name is 2john" будет выводить как:

Hello

1 my name is 

2john

Итак, я проверяю каждый символ ввода и затем решаю, стоит ли strcat это к текущей строке в array[j] или выделить другую строку array[j+1] и добавить его в начало этого.

Код выглядит следующим образом:

/*concatenates ts[i] and array[j]*/
char *add_to(char * copy, char ** array, int i , int j,int current_size){
    /* expand size of string at array[j]*/
    array[j] = realloc(array[j],sizeof(char)*(current_size+2));
    /*concate next character of ts*/
    char * target = malloc(sizeof(char)*2);
    strncpy(target,copy+i,1);
    target=strcat(target,"\0");
    array[j]=strcat(array[j],target);
    return array[j];

}

int main(int argc, char** argv){

    /*will hold literals*/
    char ** array = malloc(sizeof(char*)*1);
    /* current size */
    int array_size =1 ;
    /* terminal input */
    char * ts = *(argv+1);

    /* index of array */
    int j =0;
    /* index of terminal input */
    int i =0;
    /*current place to concatenate to in array[j] */
    int current_size=0;
    /* while there is more input */
    while(i<strlen(ts)){
    /* if we need more space */
        if(j==array_size){
            printf("%s\n","Expand");
            array_size++;
            /* assign old pointer to new pointer */
            array=realloc(array,array_size*sizeof(char*));
        }
        /* concatenate array[j] and character at ts[i]*/
        array[j]=add_to(ts,array,i,j,current_size);
        /*new spot to concatenate when loop around */
        current_size++;
        /* move onto next character of ts */
        i++;
        /*if this new character is a digit move to next slot of array */
        if(i<strlen(ts)&&isdigit(*(ts+i))!=0){
            j++;
            current_size=0;
        }   
    }
    /* print all literals in array */
    j=0;
    while(j<array_size){
        printf("%s\n",array[j]);
        j++;
    }
return 0;
}

Однако, когда ввод слишком велик, программа начинает печатать либо многобайтовые символы вместе с правильной строкой: (ؼ- 3)), либо, если даже больше, приводит к ошибке сегментации.

Любая идея, что я делаю неправильно, когда я динамически распределяю память?

1 ответ

Решение

Уменьшить и исправить ваш код:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char *add_to(char * copy, char ** array, int i , int j, int current_size){//i: start position, j: length of parts
    char *target = malloc(j + 1);//+1 for NUL
    strncpy(target, copy + i, j);
    target[j] = '\0';
    return array[current_size-1] = target;
}

int main(int argc, char** argv){
    const char *digits = "0123456789";
    char **array = NULL;
    int array_size = 0;//current size
    char *ts = argv[1];//terminal input

    int i, j;

    for(i = 0; ts[i] != '\0'; i += j){//i: index of the string
        //no need size check when expand one by one
        array = realloc(array, ++array_size * sizeof(char*));//fail check omitted
        j  = strspn(ts + i,      digits);//The length containing digit
        j += strcspn(ts + i + j, digits);//add length containing no digit
        add_to(ts, array, i, j, array_size);
    }
    /* print all string in array */
    for(j=0; j<array_size; j++){
        puts(array[j]);
    }
    //deallocate
    return 0;
}
Другие вопросы по тегам